Redux 是一个用于 JavaScript 应用的状态管理库,常与 React 配合使用。以下是关键概念与使用指南:

🧠 核心原理

  • 单向数据流:所有状态变更必须通过 dispatch 触发
  • 不可变状态:使用 immerspread operator 避免直接修改 state
  • 纯函数reducers 必须是纯函数,确保可预测性
Redux_Architecture

🛠 实践步骤

  1. 创建 store
    import { createStore } from 'redux';
    const store = createStore(reducer);
    
  2. 编写 reducer
    function reducer(state = initialState, action) {
      switch (action.type) {
        case 'ADD_TODO': return { ...state, todos: [...state.todos, action.payload] };
        default: return state;
      }
    }
    
  3. 使用 connect 链接组件:
    import { connect } from 'react-redux';
    const mapStateToProps = (state) => ({ todos: state.todos });
    

📚 扩展阅读

State_Management