在编程中,thunk 一词指的是执行延迟工作的代码部分,例如 javascript 中的异步函数。
redux 存储本身不处理异步逻辑。它只知道如何:
但是等等,如果是这样的话,我们如何调用 api 并根据它们的响应更新状态,这通常需要时间?我们该如何处理?
这就是 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 动作创建者。
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 采用两个参数:
除了让您为 api 调用创建 thunk 函数之外,createasyncthunk 还会自动调度操作来跟踪 api 请求的状态:
这真的很有用。例如,当状态处于挂起状态时,我们可以在 ui 中显示加载程序,并让用户知道正在发生某些事情。
现在我们已经创建了 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;
如果我们想在调用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中文网其它相关文章!
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
                
                                
                                
                                
                                
                                
                                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号