微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 redux 中的自定义中间件中调度异步函数

如何解决在 redux 中的自定义中间件中调度异步函数

我正在尝试创建一个自定义中间件,它根据 redux 中的某些条件分派 logout 操作(异步函数)。一旦动作被分派,它就会抛出错误 RangeError: Maximum call stack size exceeded

store.js:

const handleAction = (store) => (next) => (action) => {
  const token = loadState(TOKEN);
  const { userAccount } = store.getState();
  if (token && userAccount.email) {
    const decodedJwt = jwt_decode(token);
    if (decodedJwt.exp < dayjs().unix()) {
      store.dispatch(logoutAction());
    }
  }
  return next(action);
};

export function configureStore(initState = {}) {
  const store = createStore(
    rootReducer,initState,composeEnhancers(applyMiddleware(thunk,handleAction))
  );
  return store;
}

我做错了什么?提前致谢

解决方法

防止 logoutAction() 导致中间件分派 logoutAction() 等等...

if(action.type === 'your logoutAction type') return next(action);

示例:

const handleAction = (store) => (next) => (action) => {

  if(action.type === 'your logoutAction type') return next(action);
  
  const token = loadState(TOKEN);
  const { userAccount } = store.getState();
  if (token && userAccount.email) {
    const decodedJwt = jwt_decode(token);
    if (decodedJwt.exp < dayjs().unix()) {
      store.dispatch(logoutAction());
    }
  }
  return next(action);
};

您也可以将其与您现有的条件结合起来:

const handleAction = (store) => (next) => (action) => {     
  const token = loadState(TOKEN);
  const { userAccount } = store.getState();
  if (action.type !== 'your logoutAction type' && 
      token && 
      userAccount.email) {
    const decodedJwt = jwt_decode(token);
    if (decodedJwt.exp < dayjs().unix()) {
      store.dispatch(logoutAction());
    }
  }
  return next(action);
};

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。