什么是 thunk?
在编程中,thunk 一词指的是执行延迟工作的代码部分,例如 javascript 中的异步函数。
redux 存储本身不处理异步逻辑。它只知道如何:
同步调度动作。通过减速器更新状态。通知 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 componentsexport 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 函数的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2644659.html