React & RTK:如何从中间件调度?

Mr.*_* B. 5 reactjs react-native redux react-redux redux-toolkit

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

为了捕获全局错误,我遵循了这个例子。这工作正常,但现在我想在请求因错误而被拒绝时注销用户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);
};
Run Code Online (Sandbox Code Playgroud)

任何想法?提前致谢!

mar*_*son 10

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()或对其进行解构。dispatchapi