简体   繁体   English

如何在 aysnc function 中调用 redux 调度作为 function 的主体?

[英]How to call redux dispatch inside an aysnc function as the body of function?

i have this API helper in my react native code, but i want the user to logout everytime the jwtt token isExpired我的反应本机代码中有这个 API 助手,但我希望用户每次 jwtt 令牌过期时注销

this is the code这是代码

  const apiHelper = async (key, payload) => {
  let token = await getToken();
  //to get the currentToken from AsyncStorage
  const isTokenExpired = checkToken(token);
  //checkToken return a boolean (it is work just fine)

  const dispatch = useDispatch();

  if (isTokenExpired) {
    dispatch(logout());
    return;
  }

  //... rest of the API Helper
}

result of this code =>此代码的结果 =>

invalid hook call: Hooks can only be called inside the body of a function component.无效的钩子调用:只能在 function 组件的主体内部调用钩子。

what have i tried is calling the redux directly from the store我试过的是直接从商店调用 redux

import store from './src/redux/store';
const apiHelper = async (key, payload) => {
  let token = await getToken();
  //to get the currentToken from AsyncStorage
  const isTokenExpired = checkToken(token);
  //checkToken return a boolean (it is work just fine)

  let redux = store();

  if (isTokenExpired) {
    const { store } = redux;
    store.dispatch(logout());
    return;
  }

  //... rest of the API Helper
}

this code have no error but the state not changed to logout此代码没有错误,但 state 未更改为注销

this is the logout action这是注销操作

export const logout = () => ({type: 'AUTH_RESET'});

and the auth reducer和 auth reducer

 const initialState = () => ({
  userInfo: {},
  token: null,
  isLogin: false,
  showOnboard: true,
});

const Fetch = (state = initialState(), action = {}) => {
  switch (action.type) {
    case 'LOGIN_SUCCESS':
      const { token, ...userInfo } = action.payload;
      return {...state, userInfo, token, isLogin: true, showOnboard: null};

    case 'AUTH_RESET':
      const init = initialState()
      init.showOnboard = false
      return {...state, ...init};

    default:
      return state;
  }
};

export default Fetch;

store.js store.js

 export default () => {
  let store = createStore(persistedReducer, applyMiddleware(logger, thunk));
  let persistor = persistStore(store);
  return {store, persistor};
};

the logout action and the reducer work fine if i call it using hooks.如果我使用钩子调用它,注销操作和减速器工作正常。 but i can't get it work inside an async function.但我无法让它在异步 function 中工作。

how can i dispatch the logout inside an async function?我如何在异步 function 中调度注销?

You should have only one store in your application.您的应用程序中应该只有一个商店。 This line looks suspicious: let redux = store();这行看起来很可疑: let redux = store();

Try to import you store and call store.dispatch(action) on it.尝试导入您的商店并在其上调用store.dispatch(action)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM