Redux 和 React-Redux 从状态管理到 React 集成
学习笔记
1. Redux 是什么?
Redux 是一个用于 JavaScript 应用的状态管理库。它的核心思想是将应用的状态集中存储在一个全局的 store 中,并通过 action 和 reducer 来管理状态的更新。
核心概念:
- Store:存储应用的状态。
- Action:描述状态变化的普通对象。
- Reducer:纯函数,根据 action 更新状态。
特点:
- 与框架无关,可以用于 React、Vue、Angular 等。
- 支持中间件(如
redux-thunk
、redux-saga
)处理异步操作。
2. React-Redux 是什么?
React-Redux 是 Redux 的官方绑定库,用于将 Redux 与 React 应用连接起来。它提供了 Provider
组件和 connect
函数(或 useSelector
和 useDispatch
钩子),简化了 Redux 在 React 中的使用。
核心概念:
- Provider:将 Redux 的 store 注入 React 应用。
- connect:将 Redux 的状态和 action 映射到 React 组件的 props。
- useSelector 和 useDispatch:React Hooks,用于在函数组件中访问 Redux 的状态和派发 action。
3. Redux 和 React-Redux 的工作流程
- 定义 Action:描述状态变化。
- 定义 Reducer:根据 action 更新状态。
- 创建 Store:使用
createStore
创建 store。 - 注入 Store:使用
Provider
将 store 注入 React 应用。 - 连接组件:使用
connect
或 Hooks 将组件与 Redux 连接。
4. 代码示例
(1) 定义 Action 和 Reducer
// Action
const increment = () => ({ type: 'INCREMENT' });
// Reducer
const counterReducer = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1;
default:
return state;
}
};
(2) 创建 Store
import { createStore } from 'redux';
const store = createStore(counterReducer);
(3) 注入 Store
import { Provider } from 'react-redux';
import React from 'react';
import ReactDOM from 'react-dom';
const App = () => (
<Provider store={store}>
<Counter />
</Provider>
);
ReactDOM.render(<App />, document.getElementById('root'));
(4) 连接组件
使用
connect
(类组件):import { connect } from 'react-redux'; const Counter = ({ count, increment }) => ( <div> <p>{count}</p> <button onClick={increment}>Increment</button> </div> ); const mapStateToProps = (state) => ({ count: state }); const mapDispatchToProps = { increment }; export default connect(mapStateToProps, mapDispatchToProps)(Counter);
使用 Hooks(函数组件):
import { useSelector, useDispatch } from 'react-redux'; const Counter = () => { const count = useSelector((state) => state); const dispatch = useDispatch(); return ( <div> <p>{count}</p> <button onClick={() => dispatch(increment())}>Increment</button> </div> ); };
5. 总结
- Redux 负责管理全局状态,适用于任何 JavaScript 应用。
- React-Redux 负责将 Redux 与 React 组件连接起来,简化了状态管理在 React 中的使用。
- 通过
Provider
、connect
或 Hooks,可以轻松地将 Redux 的状态和 action 映射到 React 组件。
6. 学习建议
- 先掌握 Redux 的核心概念(store、action、reducer)。
- 再学习 React-Redux 的使用方法(
Provider
、connect
、Hooks)。 - 通过实际项目练习,加深对 Redux 和 React-Redux 的理解。