简体   繁体   English

React Native:错误:无效的挂钩调用。 钩子只能在 function 组件的主体内部调用

[英]React Native: Error: Invalid hook call. Hooks can only be called inside of the body of a function component

in my react native app I have started playing with custom hooks, I created a hook to retrive user coordinates, however when my useGeolocation hook is called (inside handleUpdateLocation method) I always get the following warning:在我的 react native 应用程序中,我开始使用自定义挂钩,我创建了一个挂钩来检索用户坐标,但是当我的 useGeolocation 挂钩被调用(在 handleUpdateLocation 方法中)时,我总是收到以下警告:

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.

Actually, all my components are functional components...实际上,我所有的组件都是功能组件......

Here is my component:这是我的组件:

//import * as React from 'react';
import { View, Text, StyleSheet,TouchableOpacity, Platform,PermissionsAndroid, BackHandler, ScrollView, TextInput, ActivityIndicator ,SafeAreaView} from 'react-native';
import React, { useState, useEffect } from 'react'
import { observer } from 'mobx-react'
import  useGeolocation  from '@hooks/useGeolocation.js';



export default OrderCard14 = observer((props) => 
{

    const handleUpdateLocation = async (gender) =>
    {
        const { coordinates, city } = useGeolocation(true);
    };

    

    return(
        <View style={{ flex:1,backgroundColor:'white',alignItems:'center',padding:0 }}>
            
    </View>
    
    
    );
        

});

And my simplified hook(removed some functions):我的简化钩子(删除了一些功能):

//import AsyncStorage from '@react-native-async-storage/async-storage';
import { AsyncStorage ,Platform, Alert, PermissionsAndroid } from 'react-native';
import _ from 'lodash';
import env from '@env/vars';
import http from '@env/axiosin';
import Geolocation from 'react-native-geolocation-service';
import { useStore } from '@hooks/use-store';


const useGeolocation = (getCityName = false) => {
    const root = useStore();
    const [coordinates, setCoordinates] = useState(false);
    const [city, setCity] = useState(false);
    


    const requestLocationPermissions = async () =>
    {
        console.log('getting new coordinates');
        if (Platform.OS === 'ios')
        {
            const auth = await Geolocation.requestAuthorization("whenInUse");
            if(auth === "granted")
            {
                //root.mapStore.setLocationEnabled(true);
                this.locationEnabled = true;
                let coords = await getMe(getCityName);
                return coords;
                /*
                const todayId = moment().isoWeekday();
                if(todayId != root.userStore.user.lastLoginDayId)
                {
                    getMe();
                }
                */
                
            }
            else
            {
                //Alert.alert('PLEASE ENABLE LOCATION');
                root.mapStore.setLocationEnabled(false);
                //this.locationEnabled = false;
            }
        }
        if (Platform.OS === 'android')
        {
            let granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
            if (granted === PermissionsAndroid.RESULTS.GRANTED) 
            {
            // do something if granted...
            
                //this.loactionEnabled = true;
                root.mapStore.setLocationEnabled(true);
                let coords = await getMe();
                return coords;
                /*
                const todayId = moment().isoWeekday();
                if(todayId != root.userStore.user.lastLoginDayId)
                {
                    getMe();
                }
                */
            }
            else
            {
                //Alert.alert('KULO');
                root.mapStore.setLocationEnabled(false);
                //this.locationEnabled = false;
            }
        }
    }


    
      useEffect(() => {
        requestLocationPermissions();
      }, []);
      console.log('returning new coordinates with hook: '+coordinates);
      return { coordinates, city };
    };
    
    export default useGeolocation;

What's exactly the problem?究竟是什么问题?

Invalid hook call.无效的挂钩调用。 Hooks can only be called inside of the body of a function component.钩子只能在 function 组件的主体内部调用。

I think they should add to the list of possible/common reasons that:我认为他们应该将以下可能/常见原因添加到列表中:

  • You might be conditionally invoking the hook call on any given render, or not invoking it at all.您可能会在任何给定的渲染上有条件地调用钩子调用,或者根本不调用它。

Hooks not only need to be inside the body of a function component, they need to be at the level of the body of the function component.钩子不仅需要位于 function 组件的主体内部,它们还需要位于 function 组件的主体级别 Always called on every render, always in the same order.总是在每次渲染时调用,总是以相同的顺序。 You have one that's inside a function:你有一个在 function 中:

const handleUpdateLocation = async (gender) =>
{
    const { coordinates, city } = useGeolocation(true);
};

Which is invalid.这是无效的。 Instead, move the hook call to the component level.相反,将挂钩调用移动到组件级别。 You can still use the resulting values inside the function:您仍然可以在 function 中使用结果值:

const { coordinates, city } = useGeolocation(true);

const handleUpdateLocation = async (gender) =>
{
    // here you can still use coordinates and city
};

In general, it's a good rule of thumb to invoke all of the hooks that you'll need as the very first thing you do in any given component.一般来说,调用所有你需要的钩子作为你在任何给定组件中做的第一件事是一个很好的经验法则。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 反应本机:.! 错误:无效的挂钩调用。 钩子只能在 function 组件的主体内部调用 - React Native !!! Error: Invalid hook call. Hooks can only be called inside of the body of a function component 反应原生。 错误:无效的挂钩调用。 钩子只能在 function 组件的主体内部调用 - React Native. Error: Invalid hook call. Hooks can only be called inside of the body of a function component 反应钩子错误:无效的钩子调用。 钩子只能在 function 组件的主体内部调用 - React hook Error: Invalid hook call. Hooks can only be called inside of the body of a function component React 17:错误:无效的钩子调用。 钩子只能在 function 组件的主体内部调用 - React 17: Error: Invalid hook call. Hooks can only be called inside of the body of a function component 错误:无效的挂钩调用。 钩子只能在 function 组件的主体内部调用。 通过路由反应 - Error: Invalid hook call. Hooks can only be called inside of the body of a function component. by Routing in react 错误:无效的挂钩调用。 钩子只能在 function 组件的主体内部调用。 - 反应 - Error: Invalid hook call. Hooks can only be called inside of the body of a function component. - React 反应,得到错误:无效的钩子调用。 Hooks 只能在函数组件的主体内部调用 - React, getting Error: Invalid hook call. Hooks can only be called inside of the body of a function component React - 错误:无效的钩子调用。 钩子只能在 function 组件的主体内部调用 - React - Error: Invalid hook call. Hooks can only be called inside of the body of a function component “错误:无效的钩子调用。只能在 function 组件的主体内部调用钩子。”在反应原生 expo - "Error: Invalid hook call. Hooks can only be called inside of the body of a function component.." in react native expo 收到此错误“无效的挂钩调用。 钩子只能在 function 组件的主体内部调用。” 在反应功能组件内? - Getting this error “Invalid hook call. Hooks can only be called inside of the body of a function component.” inside a react functional component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM