react thunk 如何使用
安装 Redux Thunk 中间件
确保项目中已安装 redux-thunk 和 redux。通过 npm 或 yarn 安装:
npm install redux-thunk redux
配置 Redux Store
在创建 Redux store 时,使用 applyMiddleware 将 thunk 中间件注入。示例代码如下:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
编写 Thunk Action Creator
Thunk 允许 action creator 返回函数而非普通 action 对象。函数接收 dispatch 和 getState 作为参数,适合处理异步逻辑。示例:
const fetchUserData = (userId) => {
return async (dispatch) => {
dispatch({ type: 'FETCH_USER_REQUEST' });
try {
const response = await fetch(`https://api.example.com/users/${userId}`);
const data = await response.json();
dispatch({ type: 'FETCH_USER_SUCCESS', payload: data });
} catch (error) {
dispatch({ type: 'FETCH_USER_FAILURE', error: error.message });
}
};
};
在组件中 Dispatch Thunk Action
通过 dispatch 调用 thunk action creator,与普通 action 使用方式一致:
import { useDispatch } from 'react-redux';
function UserComponent({ userId }) {
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchUserData(userId));
}, [dispatch, userId]);
}
处理异步逻辑的注意事项
- 错误处理:在 thunk 中捕获异常并 dispatch 失败 action。
- 加载状态:通过
FETCH_USER_REQUEST等 action 更新加载状态。 - 取消请求:可结合
AbortController实现请求取消(需在 cleanup 函数中调用)。
结合 Redux Toolkit 使用
若使用 @reduxjs/toolkit,其 configureStore 已默认包含 thunk 中间件,无需手动配置:
import { configureStore } from '@reduxjs/toolkit';
import rootReducer from './reducers';
const store = configureStore({
reducer: rootReducer
});






