【问题标题】:Invalid hook call When Call useDispatch in global function?在全局函数中调用useDispatch时挂钩调用无效?
【发布时间】:2021-06-17 06:58:36
【问题描述】:

代码 ::

import {Alert} from 'react-native';
import action from './../Redux/Actions/auth';
import {useDispatch, useSelector, useStore} from 'react-redux';
import AsyncStorage from '@react-native-async-storage/async-storage';

export const logoutFromApp = (message) => {
  if (
    message === 'Unauthorized!' ||
    message === 'Unactivite' ||
    message === 'No token provided!'
  ) {
    Alert.alert(
      'App',
      'Your account is deactivated or unauthorized, please try again to login.',
      [
        {
          text: 'ok',
          onPress: () => {
            AsyncStorage.clear();
            const dispatch = useDispatch();
            dispatch(action.logout());
          },
        },
      ],
    );
  } else {
    alert(message);
  }
};

错误:

【问题讨论】:

    标签: reactjs react-native redux react-redux redux-thunk


    【解决方案1】:

    如果你想在非反应函数中使用 dispatch 你可以使用 store.dispatch()

    import {store} from "location of store" 
    export const logoutFromApp = (message) => {
      if (
        message === 'Unauthorized!' ||
        message === 'Unactivite' ||
        message === 'No token provided!'
      ) {
        Alert.alert(
          'App',
          'Your account is deactivated or unauthorized, please try again to login.',
          [
            {
              text: 'ok',
              onPress: () => {
                AsyncStorage.clear();
                
               store.dispatch(action.logout());
              },
            },
          ],
        );
      } else {
        alert(message);
      }
    };
    

    【讨论】:

      【解决方案2】:

      正确 - React hooks can only be called in the top-level body of a function component。

      这里更好的方法是rewrite logoutFromApp as a Redux thunk,然后在您的组件中dispatch(logoutFromApp("abcd"))。

      【讨论】:

        猜你喜欢
        • 2021-03-31
        • 2021-12-07
        • 1970-01-01
        • 1970-01-01
        • 2014-12-24
        • 1970-01-01
        • 2020-08-13
        • 1970-01-01
        • 2021-02-13
        相关资源
        最近更新 更多