react如何使用redux
安装 Redux 相关依赖
在 React 项目中安装 Redux 核心库和 React-Redux 绑定库:
npm install redux react-redux
如果需要异步操作(如 API 调用),还需安装中间件如 redux-thunk:
npm install redux-thunk
创建 Redux Store
定义初始状态、Reducer 和 Store。Reducer 是一个纯函数,接收当前状态和 action,返回新状态。

// store.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
// 初始状态
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, applyMiddleware(thunk));
export default store;
使用 Provider 包裹应用
在根组件(如 App.js)中通过 Provider 提供 Store,使所有子组件可访问 Redux 状态。
// App.js
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
使用 connect 或 Hooks(useSelector 和 useDispatch)访问状态和派发 action。

方法 1:使用 connect(类组件)
// Counter.js
import React from 'react';
import { connect } from 'react-redux';
class Counter extends React.Component {
render() {
return (
<div>
<p>Count: {this.props.count}</p>
<button onClick={this.props.increment}>Increment</button>
<button onClick={this.props.decrement}>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)(Counter);
方法 2:使用 Hooks(函数组件)
// Counter.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
function Counter() {
const count = useSelector((state) => state.count);
const dispatch = useDispatch();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
</div>
);
}
export default Counter;
处理异步操作
使用 redux-thunk 派发异步 action,例如调用 API:
// actions.js
export const fetchData = () => {
return async (dispatch) => {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
dispatch({ type: 'SET_DATA', payload: data });
} catch (error) {
dispatch({ type: 'FETCH_ERROR', error });
}
};
};
// 在组件中调用
dispatch(fetchData());
组织代码结构
推荐按功能模块拆分 Redux 代码(Ducks 模式):
- 将 action types、action creators 和 reducer 放在同一文件(如
counterSlice.js)。 - 使用
combineReducers合并多个 reducer(适用于大型应用)。
// counterSlice.js
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
export const increment = () => ({ type: INCREMENT });
export const decrement = () => ({ type: DECREMENT });
const initialState = { count: 0 };
export default function reducer(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;
}
}






