redux如何在react使用
Redux 在 React 中的使用方法
安装依赖
确保项目已安装 redux 和 react-redux。通过以下命令安装:
npm install redux react-redux
创建 Redux Store
在 store.js 文件中定义全局状态和 reducer:
import { createStore } from 'redux';
// 初始状态
const initialState = {
count: 0
};
// Reducer 函数
const rootReducer = (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(rootReducer);
export default store;
连接 React 应用
在根组件(如 App.js)中通过 Provider 提供 Store:
import React from 'react';
import { Provider } from 'react-redux';
import store from './store';
import Counter from './Counter';
function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}
export default App;
组件中使用 Redux
在子组件中通过 useSelector 和 useDispatch 访问状态和触发动作:

import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
function Counter() {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
return (
<div>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>-</button>
<span>{count}</span>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>+</button>
</div>
);
}
export default Counter;
异步操作处理
使用 redux-thunk 或 redux-saga 处理异步逻辑。以 redux-thunk 为例:
-
安装中间件:
npm install redux-thunk -
修改 Store 配置:

import { applyMiddleware, createStore } from 'redux'; import thunk from 'redux-thunk';
const store = createStore(rootReducer, applyMiddleware(thunk));
3. 定义异步 Action:
```javascript
const asyncIncrement = () => {
return (dispatch) => {
setTimeout(() => {
dispatch({ type: 'INCREMENT' });
}, 1000);
};
};
// 在组件中调用
dispatch(asyncIncrement());
代码组织规范
建议按功能模块拆分 Redux 逻辑:
actions/: 定义 action creatorsreducers/: 拆分多个 reducer 并用combineReducers合并store.js: 集中配置 Store
示例模块化结构:
// reducers/index.js
import { combineReducers } from 'redux';
import counterReducer from './counterReducer';
export default combineReducers({
counter: counterReducer
});
性能优化
- 使用
React.memo避免不必要的组件渲染 - 在
useSelector中返回最小必要状态 - 考虑使用
reselect创建记忆化 selector
通过以上步骤,可以完整实现 Redux 在 React 中的集成与管理。






