React Native 错误:无效的挂接调用,尝试调用挂接时...已遵循建议的解决方案

vq8itlhq  于 2022-12-14  发布在  React
关注(0)|答案(1)|浏览(127)

尝试使用挂钩时出现此错误

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 ( 

...
...
...

我相信我使用它是正确的..我不知道还有什么要检查的。

2izufjch

2izufjch1#

您的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 ( 

...
...

它工作正常。

相关问题