1

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

商店.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;
}

我究竟做错了什么?提前致谢

4

1 回答 1

2

防止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);
};
于 2021-02-05T13:59:41.580 回答