gpt4 book ai didi

reactjs - 使用 redux 工具包时定义操作中的副作用(不是异步 thunk)的正确方法是什么?

转载 作者:行者123 更新时间:2023-12-04 07:58:05 27 4
gpt4 key购买 nike

目前,我正在使用 Typescript 深入研究 Redux Toolkit,但遇到了注销操作。它基本上根本不应该有任何有效载荷,但应该修改 localStorage 和 axios 配置。我知道有两种工作方式略有不同。

一种是在 createSlice 中使用 prepare 回调定义 reducer:

const authSlice = createSlice({
name: "authentication",
initialState,
reducers: {
logout: {
reducer: () => initialState,
prepare: () => {
api.logout();
return { payload: undefined, error: undefined, meta: undefined };
},
},
},...

在这种情况下,prepare 回调的类型签名强制我显式返回 payloaderrormeta 属性。

另一种方法是将 createActionprepare 回调一起使用:

export const logout = createAction("authentication/logout", () => {
api.logout();
return { payload: undefined };
});

这是一个更好看的解决方案。至少我不必传递 errormeta。但仍然被迫返回 payload,即使它不需要。

有点困惑为什么 prepare 函数签名不同,但这不是重点。

我的问题是您将如何处理此类情况。也许我做错了什么?

我知道还有使用中间件的选项,但是设置只处理一个操作的中间件看起来像是一项开销。

最佳答案

你在这里有点混淆术语 - 并且遗漏了一个重要的术语;)

action 是具有 type 属性的对象。您永远不能在那里执行代码。

action creator 是一个返回action 的函数。您可以在此处执行代码,但它将在分派(dispatch)结果操作之前执行。

async thunkthunk 的一种特殊形式,它将生命周期操作(挂起/完成/拒绝)附加到 thunk。确切地说,createAsyncThunk 函数创建了一个async thunk 操作创建器 - 一个创建您可以调度以使其被触发的东西的函数。

那么,缺少的东西:什么是 thunk

thunk 是一个被分派(dispatch)的函数,然后由 redux-thunk 中间件执行。该函数将作为第一个参数传递给 dispatch,作为第二个参数传递给 getState,因此您可以在必要时从那里触发更多与 redux 相关的东西。

所以你正在寻找一个thunk。通常,这些是用 Action 创建器编写的,因此您正在寻找 thunk Action 创建器

const logout = (potentiallySomeArgument) => (dispatch, getState) => {
api.logout(potentiallySomeArgument);
// maybe you also want to dispatch an action to clear state
dispatch(userSlice.clear())
}

这将像任何其他操作一样被分派(dispatch),因此功能与您的组件完全无关:

dispatch(logout("whatever"))

关于reactjs - 使用 redux 工具包时定义操作中的副作用(不是异步 thunk)的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66600680/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com