gpt4 book ai didi

reactjs - react & RTK : How to dispatch from a middleware?

转载 作者:行者123 更新时间:2023-12-05 09:04:32 38 4
gpt4 key购买 nike

我正在使用 RTK(Redux 工具包)和 RTK 查询来管理我的商店和 API 请求。

为了在全局范围内捕获错误,我遵循了 this example .这工作正常,但现在我想在请求因 401 - Unauthorized-error 而被拒绝时注销用户。

const rtkQueryErrorLogger = api => next => action => {
if (isRejectedWithValue(action)) {
if (action.payload.status === 401) {
// Reset the store (not working)
const dispatch = useDispatch();
const dipatch(logout());

// Forward to login-screen (not working)
const navigation = useNavigation();
navigation.push('Login');
}
}
return next(action);
};

有什么想法吗?提前致谢!

最佳答案

Redux 中间件总是获取一个“mini-store API”对象作为最外层函数的参数,该函数包含 {dispatch, getState}:

https://redux.js.org/tutorials/fundamentals/part-4-store#writing-custom-middleware

在这种情况下,它是您示例中名为 api 的变量。

您可以从该对象访问 dispatch 并随时在您的中间件内分派(dispatch)一个 Action 。只需删除 const dispatch = useDispatch 行,然后将下一行更改为 api.dispatch() 或从 中解构 dispatch api 声明中的对象。

关于reactjs - react & RTK : How to dispatch from a middleware?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68520342/

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