Redux 是一个用于 JavaScript 应用的状态管理库,常与 React 配合使用。以下是关键概念与使用指南:
🧠 核心原理
- 单向数据流:所有状态变更必须通过
dispatch
触发 - 不可变状态:使用
immer
或spread operator
避免直接修改 state - 纯函数:
reducers
必须是纯函数,确保可预测性
🛠 实践步骤
- 创建
store
:import { createStore } from 'redux'; const store = createStore(reducer);
- 编写
reducer
:function reducer(state = initialState, action) { switch (action.type) { case 'ADD_TODO': return { ...state, todos: [...state.todos, action.payload] }; default: return state; } }
- 使用
connect
链接组件:import { connect } from 'react-redux'; const mapStateToProps = (state) => ({ todos: state.todos });
📚 扩展阅读
- 深入学习Redux 探索中间件与异步操作
- React与Redux实战 查看完整代码示例