错误:无效钩子调用.当尝试调用hook..遵循建议的决议



尝试使用钩子

时出现此错误
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

我检查了,我没有不匹配的版本,我在同一个应用程序中没有一个以上的react副本这就是我如何使用我的钩子。

我是这样使用我的钩子的:

import messaging from '@react-native-firebase/messaging'


const Stack = createStackNavigator()



if (!firebase.apps.length) {
firebase.initializeApp(FIREBASE_CONFIG)
}



export default function App() {

// Request Push Notification permission from device.
const requestPermission = async () => {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
console.log('Authorization status:', authStatus);
}
};
useEffect(() => {
requestPermission();
}, []);

return ( 
...
...
...

我相信我用对了…我不知道还需要检查什么

你的useEffect代码在内部函数内,你需要把它放在函数外,并确保你的useEffect在主函数内。

更新后的代码是这样的

export default function App() {
useEffect(() => {
requestPermission();
}, []);
// Request Push Notification permission from device.
const requestPermission = async () => {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED || authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
console.log('Authorization status:', authStatus);
}
};


return ( 
...
...

It's works fine.

最新更新