返回

极简React全局状态管理,一学就会

前端

前言

大家好,我是阳九,一个中途转行的野路子码农,热衷于研究和手写前端工具。我的宗旨就是万物皆可手写。新手创作不易,有问题欢迎指出和轻喷,谢谢。

本文适合有一定React开发经验,并且对Redux有一定了解的开发者。

什么是Redux?

Redux是一个流行的状态管理库,可帮助我们更轻松地管理应用状态。Redux的基本思想是将应用的状态存储在一个中心化的store中,然后通过reducer来更新store中的状态。

Redux的基本概念

在Redux中,有以下几个基本概念:

  • Store: store是Redux中的核心组件,它负责存储应用的全局状态。
  • Reducer: reducer是纯函数,它接收当前的状态和一个action,然后返回一个新的状态。
  • Action: action是一个对象,它了需要在store中执行的操作。

如何使用Redux?

使用Redux的步骤如下:

  1. 创建一个store。
  2. 创建reducer。
  3. 将reducer注册到store中。
  4. 在组件中使用store。

一个简单的Redux应用

下面,我们将构建一个简单的Redux应用,以帮助你理解Redux是如何工作的。

首先,我们需要创建一个store。我们可以使用createStore()函数来创建一个store:

const store = createStore(reducer);

接下来,我们需要创建reducer。reducer是一个纯函数,它接收当前的状态和一个action,然后返回一个新的状态。例如,我们可以创建一个简单的reducer,它负责更新store中的count状态:

function reducer(state = { count: 0 }, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { ...state, count: state.count + 1 };
    case 'DECREMENT':
      return { ...state, count: state.count - 1 };
    default:
      return state;
  }
}

接下来,我们需要将reducer注册到store中。我们可以使用store.registerReducer()方法来注册reducer:

store.registerReducer('count', reducer);

现在,我们可以在组件中使用store了。我们可以使用useSelector()钩子函数来获取store中的状态,并使用useDispatch()钩子函数来分发action:

import { useSelector, useDispatch } from 'react-redux';

const MyComponent = () => {
  const count = useSelector((state) => state.count);
  const dispatch = useDispatch();

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
      <button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
    </div>
  );
};

结语

Redux是一个流行的状态管理库,可帮助我们更轻松地管理应用状态。在本文中,我们探讨了Redux的基本概念,并构建了一个简单的Redux应用。希望本文能帮助你理解Redux是如何工作的。