react redux如何使用
React Redux 使用指南
React Redux 是 React 和 Redux 的官方绑定库,用于在 React 应用中高效管理全局状态。以下是核心使用方法:
安装依赖
确保项目已安装 React、Redux 和 React Redux:
npm install redux react-redux
创建 Redux Store
定义应用的状态管理中心:

import { createStore } from 'redux';
// 初始状态
const initialState = { count: 0 };
// reducer 函数
function counterReducer(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;
}
}
// 创建 store
const store = createStore(counterReducer);
使用 Provider 包裹应用
在根组件中注入 store:
import { Provider } from 'react-redux';
function App() {
return (
<Provider store={store}>
<CounterComponent />
</Provider>
);
}
连接组件与 Redux
使用 useSelector 和 useDispatch Hook(函数组件):

import { useSelector, useDispatch } from 'react-redux';
function CounterComponent() {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
</div>
);
}
类组件连接方式(可选)
使用 connect 高阶组件:
import { connect } from 'react-redux';
class CounterComponent extends React.Component {
render() {
return (
<div>
<p>Count: {this.props.count}</p>
<button onClick={this.props.increment}>+</button>
<button onClick={this.props.decrement}>-</button>
</div>
);
}
}
const mapStateToProps = state => ({ count: state.count });
const mapDispatchToProps = dispatch => ({
increment: () => dispatch({ type: 'INCREMENT' }),
decrement: () => dispatch({ type: 'DECREMENT' })
});
export default connect(mapStateToProps, mapDispatchToProps)(CounterComponent);
异步操作处理
结合 Redux Thunk 或 Redux Saga 中间件处理异步逻辑(以 Thunk 为例):
// 安装中间件
npm install redux-thunk
// 配置 store
import { applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(reducer, applyMiddleware(thunk));
// 定义异步 action
function fetchData() {
return dispatch => {
fetch('/api/data')
.then(res => res.json())
.then(data => dispatch({ type: 'SET_DATA', payload: data }));
};
}
最佳实践
- 将 action types 定义为常量避免拼写错误
- 使用 action creators 封装 action 对象
- 拆分多个 reducer 并使用
combineReducers - 避免直接修改 state,始终返回新对象
通过以上步骤可以快速在 React 应用中集成 Redux 进行状态管理。现代 React 项目推荐优先使用 Redux Toolkit 简化配置流程。





