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 Creator
Thunk 允许 action creator 返回函数而非普通 action 对象。函数接收 dispatch 和 getState 作为参数:
const fetchUserData = (userId) => {
return (dispatch) => {
dispatch({ type: 'FETCH_USER_REQUEST' });
fetch(`https://api.example.com/users/${userId}`)
.then(response => response.json())
.then(data => dispatch({ type: 'FETCH_USER_SUCCESS', payload: data }))
.catch(error => dispatch({ type: 'FETCH_USER_FAILURE', error }));
};
};
在组件中调用异步 Action
通过 dispatch 调用异步 action,与同步 action 使用方式一致:
import { useDispatch } from 'react-redux';
function UserComponent({ userId }) {
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchUserData(userId));
}, [dispatch, userId]);
}
处理复杂异步逻辑
Thunk 支持多级异步操作或条件调度。例如链式请求:
const fetchUserAndPosts = (userId) => {
return async (dispatch) => {
const user = await fetchUser(userId);
dispatch({ type: 'SET_USER', payload: user });
const posts = await fetchPosts(user.id);
dispatch({ type: 'SET_POSTS', payload: posts });
};
};
访问当前状态
通过 getState 参数可获取当前 Redux 状态,实现条件调度:
const loadDataIfNeeded = () => {
return (dispatch, getState) => {
const { isLoading } = getState().user;
if (!isLoading) {
dispatch(fetchUserData());
}
};
};






