Redux 是一个用于管理 JavaScript 应用程序状态的库。它通过中央存储(也称为状态树)来维护所有组件的状态,并允许开发者通过派发(dispatch)动作来更新状态。

安装

要开始使用 Redux,首先需要安装它:

npm install redux

或者

yarn add redux

基本概念

Action

动作(Action)是一个描述发生了什么的普通对象。它携带信息,但是不直接修改状态。

const increment = { type: 'INCREMENT' };

Reducer

还原器(Reducer)是纯函数,它接受当前的 state 和一个 action,并返回新的 state。

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

Store

Redux 的 Store 是唯一的状态树,它将 action 和 reducer 联系起来。

import { createStore } from 'redux';

const store = createStore(counter);

使用 Redux

在你的组件中,你可以通过 connect 高阶组件或 mapStateToPropsmapDispatchToProps 函数来连接到 Redux。

import { connect } from 'react-redux';

const mapStateToProps = state => ({
  count: state
});

const mapDispatchToProps = dispatch => ({
  increment: () => dispatch({ type: 'INCREMENT' }),
  decrement: () => dispatch({ type: 'DECREMENT' })
});

export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);

更多信息

想了解更多关于 Redux 的内容,请访问我们的文档:Redux 官方文档

[center]Redux