[英]Invalid hook call When Call useDispatch in global function?
Code::代码::
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);
}
};
Error:错误:
Correct - React hooks can only be called in the top-level body of a function component .正确 - React 钩子只能在 function 组件的顶层主体中调用。
A better approach here would be to rewrite logoutFromApp
as a Redux thunk , and then dispatch(logoutFromApp("abcd"))
from within your component.这里更好的方法是将
logoutFromApp
重写为 Redux thunk ,然后从组件中dispatch(logoutFromApp("abcd"))
。
If you want to use dispatch in a non react function you can use store.dispatch()如果你想在非反应 function 中使用调度,你可以使用 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);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.