当前位置:首页 > React

react thunk 如何使用

2026-01-16 09:05:41React

使用 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 对象。函数接收 dispatchgetState 作为参数:

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());
    }
  };
};

react thunk 如何使用

分享给朋友:

相关文章

react 如何引入jquery

react 如何引入jquery

引入 jQuery 到 React 项目 在 React 项目中引入 jQuery 可以通过多种方式实现,但需要注意 React 和 jQuery 操作 DOM 的方式可能冲突,因此建议仅在必要时使用…

如何下载react

如何下载react

下载 React 的方法 通过 npm 或 yarn 安装 React 可以通过包管理器 npm 或 yarn 安装。确保已安装 Node.js(包含 npm),然后在项目目录中运行以下命令:…

react如何运行

react如何运行

运行React项目的步骤 安装Node.js 确保系统已安装Node.js(建议版本12以上),可从官网下载并安装。Node.js自带npm包管理器,用于后续依赖安装。 创建React项目 使用官方…

如何用react

如何用react

使用React的基本步骤 安装Node.js和npm 确保系统已安装Node.js和npm。Node.js自带npm,可从官网下载安装包。安装完成后,通过命令行验证版本: node -v npm -…

如何启动react

如何启动react

安装Node.js 确保系统已安装Node.js(建议使用LTS版本),可通过官网下载并安装。安装完成后,在终端运行以下命令验证版本: node -v npm -v 创建React项目 使用官方工具…

react如何重启

react如何重启

重启 React 应用的方法 重新加载当前页面 使用 window.location.reload() 强制刷新页面,这会重新加载整个应用并重置所有状态。 window.location.re…