react如何使用dispatch
使用 useDispatch 钩子
在 React 组件中,通过 react-redux 提供的 useDispatch 钩子获取 dispatch 函数:

import { useDispatch } from 'react-redux';
function MyComponent() {
const dispatch = useDispatch();
// 调用 dispatch 触发 action
dispatch({ type: 'ACTION_TYPE', payload: data });
}
触发同步 Action
直接传递 action 对象或通过 action creator 生成 action:

// 直接传递 action 对象
dispatch({ type: 'INCREMENT', payload: 1 });
// 使用 action creator
const increment = (amount) => ({ type: 'INCREMENT', payload: amount });
dispatch(increment(5));
触发异步 Action
通过中间件(如 redux-thunk)处理异步逻辑时,dispatch 可接受函数:
const fetchData = () => async (dispatch) => {
dispatch({ type: 'FETCH_START' });
try {
const response = await api.get('/data');
dispatch({ type: 'FETCH_SUCCESS', payload: response.data });
} catch (error) {
dispatch({ type: 'FETCH_ERROR', payload: error });
}
};
// 在组件中调用
dispatch(fetchData());
结合 useSelector 使用
通常与 useSelector 配合,实现状态读取与更新:
import { useSelector } from 'react-redux';
function Counter() {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
return (
<button onClick={() => dispatch({ type: 'INCREMENT' })}>
Count: {count}
</button>
);
}
注意事项
- 依赖注入:确保组件被
<Provider store={store}>包裹,否则useDispatch会报错。 - 性能优化:避免在渲染中频繁创建新的 action 对象,建议将 action creator 移到组件外部。
- TypeScript 类型:为
dispatch添加类型以增强安全性:const dispatch: AppDispatch = useDispatch();






