首页 > web前端 > js教程 > 正文

Redux 工具包:创建 Thunk 函数

花韻仙語
发布: 2024-12-23 14:46:10
转载
839人浏览过

什么是 thunk?

在编程中,thunk 一词指的是执行延迟工作的代码部分,例如 javascript 中的异步函数。

redux 存储本身不处理异步逻辑。它只知道如何:

  1. 同步调度动作。
  2. 通过减速器更新状态。
  3. 通知 ui 有关状态更改的信息。

但是等等,如果是这样的话,我们如何调用 api 并根据它们的响应更新状态,这通常需要时间?我们该如何处理?

这就是 thunk 函数的用武之地。

什么是 thunk 函数?

thunk 函数是为处理异步逻辑(例如调用 api)而创建的函数。它需要两个参数dispatch和getstate来调度动作,并在需要时访问当前状态。

const getallusers = () => {
  return async (dispatch, getstate) => {
    dispatch(fetingallusers());
    try {
      const users = await getusers();
      dispatch(userupdated(users));
    } catch (err) {
      dispatch(logerror(err))
    }
  }
}
登录后复制

返回的函数是 thunk 函数,getallusers 在本例中被称为 thunk 动作创建者,它将像这样调度:

dispatch(getallusers())
登录后复制

如果需要,可以使用 thunk 函数中使用的参数来调度 thunk 动作创建者。

使用 createasyncthunk 创建 thunk

redux toolkit 提供了 createasyncthunk api 来轻松生成 thunk:

import { createasyncthunk } from '@reduxjs/toolkit';

export const fetchuserbyid = createasyncthunk(
  'user/fetchuserbyid',
  async (userid) => {
    const user = await somehttprequest(userid);
    return user;
  }
);
登录后复制

fetchuserbyid 是这里创建的 thunk 函数。 createasyncthunk 采用两个参数:

  • 第一个参数是用于生成的操作类型的字符串前缀(例如 user/fetchuserbyid/pending、user/fetchuserbyid/fulfilled 或 user/fetchuserbyid/rejected)。
  • 第二个参数是“有效负载创建者”函数。它应该返回一个包含所需数据或错误的 promise。

为什么使用createasyncthunk?

除了让您为 api 调用创建 thunk 函数之外,createasyncthunk 还会自动调度操作来跟踪 api 请求的状态:

  • 待处理:请求正在进行中。
  • fulmeded:请求成功。
  • 被拒绝:请求失败。

这真的很有用。例如,当状态处于挂起状态时,我们可以在 ui 中显示加载程序,并让用户知道正在发生某些事情。

在切片中使用 thunk

现在我们已经创建了 fetchuserbyid thunk,我们可以使用 userslice 中的 extrareducers 字段来处理状态状态更改:

import { createslice } from '@reduxjs/toolkit';

const initialstate = {
  user: null,
  status: 'idle', // 'idle' | 'pending' | 'succeeded' | 'failed'
  error: null,
};

export const userslice = createslice({
  name: 'user',
  initialstate,
  reducers: {
    usernameupdated: (state, action) => {
      state.user.username = action.payload;
    },
    emailupdated: (state, action) => {
      state.user.email = action.payload;
    },
    userdatacleared: (state) => {
      state.user = null;
      state.status = 'idle';
    },
  },
  extrareducers: (builder) => {
    builder
      .addcase(fetchuserbyid.pending, (state) => {
        state.status = 'pending';
      })
      .addcase(fetchuserbyid.fulfilled, (state, action) => {
        state.status = 'succeeded';
        state.user = action.payload;
      })
      .addcase(fetchuserbyid.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.error.message || 'something went wrong.';
      });
  },
});

export const { usernameupdated, emailupdated, userdatacleared } = userslice.actions;

// selector for the status to use in the application's components
export const selectstatus = (state) => state.user.status;
登录后复制

createasyncthunk 条件

如果我们想在调用api之前检查一些条件怎么办?例如,如果状态已经处于待处理状态,我们不想调用它两次。在这种情况下,我们可以使用 createasyncthunk 接受的第三个参数来写入条件。

export const fetchUserById = createAsyncThunk(
  "user/fetchUserById",
  async (userId) => {
    const response = await someHttpRequest(userId);
    return response;
  },
  {
    condition(_, { getState }) {
      const status = selectStatus(getState());
      if (status !== "idle") {
        return false;
      }
    },
  }
);
登录后复制

要了解如何将 typescript 与 thunk 函数结合使用,请阅读类型检查 redux thunk。

以上就是Redux 工具包:创建 Thunk 函数的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号