在全局函数中调用 useDispatch 时挂钩调用无效?

Invalid hook call When Call useDispatch in global function?

代码::

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);
  }
};

错误:

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

此处更好的方法是 rewrite logoutFromApp as a Redux thunk,然后从您的组件中 dispatch(logoutFromApp("abcd"))

如果你想在非 React 函数中使用分派,你可以使用 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);
  }
};