React & RTK:如何从中间件发送?

React & RTK: How to dispatch from a middleware?

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

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

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 并随时在您的中间件内发送一个动作。只需删除 const dispatch = useDispatch 行,然后将下一行更改为 api.dispatch() 或从声明中的 api 对象解构 dispatch