react thunk 如何使用
使用 React Thunk 的基本步骤
安装 Redux 和 Redux Thunk 作为依赖项:
npm install redux redux-thunk
在 Redux store 配置中应用 Thunk 中间件:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const store = createStore(rootReducer, applyMiddleware(thunk));
创建异步 Action
Thunk 允许 action creator 返回函数而非普通 action 对象。该函数接收 dispatch 和 getState 作为参数:
const fetchUser = (userId) => {
return async (dispatch) => {
dispatch({ type: 'FETCH_USER_REQUEST' });
try {
const response = await fetch(`/api/users/${userId}`);
const user = await response.json();
dispatch({ type: 'FETCH_USER_SUCCESS', payload: user });
} catch (error) {
dispatch({ type: 'FETCH_USER_FAILURE', error: error.message });
}
};
};
在组件中调用异步 Action
通过 useDispatch 或 connect 派发异步 action:
import { useDispatch } from 'react-redux';
function UserProfile({ userId }) {
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchUser(userId));
}, [dispatch, userId]);
}
处理多个异步操作
Thunk 可以组合多个异步操作或条件派发:
const fetchPostsIfNeeded = () => {
return (dispatch, getState) => {
if (getState().posts.shouldFetch) {
dispatch(fetchPosts());
}
};
};
错误处理最佳实践
在异步操作中统一捕获错误并派发失败 action:
const updateUser = (userData) => {
return async (dispatch) => {
try {
const response = await api.updateUser(userData);
dispatch({ type: 'UPDATE_SUCCESS', payload: response });
} catch (error) {
dispatch({ type: 'UPDATE_FAILURE', error });
throw error; // 允许组件捕获错误
}
};
};






