【问题标题】:How to call redux dispatch inside an aysnc function as the body of function?如何在异步函数中调用 redux 调度作为函数体?
【发布时间】:2021-07-31 03:36:09
【问题描述】:

我的 react 本机代码中有这个 API 助手,但我希望用户每次 jwtt 令牌过期时注销

这是代码

  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
}

这段代码的结果 =>

无效的钩子调用:钩子只能在主体内部调用 功能组件。

我尝试过的是直接从商店调用 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
}

此代码没有错误但状态未更改为注销

这是注销操作

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

和 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

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

如果我使用钩子调用它,注销操作和减速器工作正常。 但我无法让它在异步函数中工作。

如何在异步函数中调度注销?

【问题讨论】:

    标签: javascript redux react-redux axios jwt


    【解决方案1】:

    您的应用程序中应该只有一个商店。这行看起来很可疑:let redux = store();

    尝试导入您的商店并致电store.dispatch(action)

    【讨论】:

    • 如果你从 store.js 调用 store 函数,它会给你一个新的 store。您的应用程序中应该只有一个商店。试试这个:``` const store = createStore(...) export {store} ```
    • 你不能在反应组件之外调用钩子
    • 你想要做的应该进入中间件。 const apiMiddleware = (store) => (action) => (next) => { if(action.type === "SOME_TYPE"){ store.dispatch(logout()) } }
    • 我看到你有“thunk”。用那个。 const logout = () => { return dispatch => { dispatch(action) } } // 在 react 组件中 const dispatch = useDispatch() dispatch(logout()) // 在连接函数中 const mapDispatchToProps = dispatch => { return { 注销:() => 调度(注销()) } }
    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 2020-03-09
    • 2021-12-11
    • 2020-04-26
    • 2020-12-20
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多