Redux 是一个用于管理 JavaScript 应用程序状态库。它是由 Facebook 开发并维护的,被广泛应用于 React 应用程序中。以下是 Redux 的基本概念和用法概述。

基本概念

  • State:应用的状态,通常以对象的形式存储。
  • Action:一个描述发生了什么的普通对象,它是异步数据流中唯一的数据载体。
  • Reducer:纯函数,用于更新 state。
  • Store:将所有组件连接到一起的对象。

快速开始

要开始使用 Redux,首先需要创建一个 store。以下是一个简单的例子:

import { createStore } from 'redux';

const initialState = {
  count: 0
};

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

const store = createStore(reducer);

Action 创建

Action 是一个描述发生了什么的普通对象。通常,我们会创建一个函数来返回 Action:

function increment() {
  return { type: 'INCREMENT' };
}

function decrement() {
  return { type: 'DECREMENT' };
}

Store 订阅

可以通过 store.subscribe() 方法来订阅 store 的变化:

store.subscribe(() => {
  console.log('当前状态:', store.getState());
});

每次 state 发生变化时,都会调用订阅的函数。

组件连接到 Store

使用 connect 高阶组件可以将 React 组件连接到 Redux store:

import { connect } from 'react-redux';

const Counter = ({ count, increment, decrement }) => (
  <div>
    <p>计数: {count}</p>
    <button onClick={increment}>增加</button>
    <button onClick={decrement}>减少</button>
  </div>
);

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

const mapDispatchToProps = dispatch => ({
  increment: () => dispatch(increment()),
  decrement: () => dispatch(decrement())
});

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

更多关于 Redux 的详细内容,请访问我们的 Redux 官方文档

相关资源


Redux 是一个强大的工具,可以帮助你更好地管理复杂的应用程序状态。希望这份文档能帮助你快速上手。如果你有任何疑问或需要进一步的帮助,请访问我们的社区论坛。🤝