React Hook“ useState”或React Hook“ useEffect”在都不是React函数的函数中被调用

时间:2020-04-12 19:18:37

标签: javascript reactjs react-hooks

TL; DR:,我的目标是分离 API函数,并在需要时将其导入。然后在componentDidMount情况下呼叫他们。另外,有人告诉我asyncawait将与之一起使用,因为:getCurrentPosition是一个异步函数。


3 个答案:

答案 0 :(得分:2)

首先,您必须在React功能组件(而不是类)中调用该钩子。

docs

Hooks ...让您无需编写类即可使用状态和其他React功能。

仅来自React函数的调用挂钩

第二,将getGeolocation更改为useGeolocation

docs

自定义Hook是一个JavaScript函数,其名称以“ use”开头...

如果函数不是以“ use”开头,React不会将其视为钩子,也不允许您在其中调用钩子

答案 1 :(得分:1)

您不能在类内部调用钩子。挂钩只能在无状态组件内部调用。如果您想访问该信息,则应该在HOC中对其进行转换,或者在函数中对componentDidMount的类进行转换。 https://reactjs.org/docs/hooks-faq.html#what-can-i-do-with-hooks-that-i-couldnt-with-classes

答案 2 :(得分:1)

解决问题所需的所有提示均在错误代码中

  1. 挂钩或自定义挂钩应在功能组件内使用
  2. 自定义钩子是可以像函数一样调用的钩子。但是,必须在其前面加上use,以使React知道这是一个自定义钩子

根据上述条件,您的Weather组件是一个类组件,您需要将其转换为Functional组件,或者避免将geolocation用作自定义钩子

第二,由于geoLocation是自定义挂钩,因此您必须将其命名为useGetLocation

import React from 'react';
import { useGetLocation } from './getlocation';

const Weather =  (props) =>  {
    const geoLocation = useGetLocation();
    useEffect(() => {
        document.title = "Weather";
    }, []);

    return(
        <>
        <h1>Weather</h1>
        <h2>{React.version}</h2>
        </>
    );
}

export default Weather;

import {useState, useEffect} from 'react';

export const useGetLocation = () => {
    const [position, setPosition] = useState({});
    const [error, setError] = useState(null);

    const successHandler = ({coords}) => {
        setPosition({
            latitude: coords.latitude,
            longitude: coords.longitude
        });
    };

    const errorHandler = (error) => { setError(error.message); };

    useEffect(() => {
        if (!navigator.geolocation) {
            setError("Geolocation might not be supported.");
            return;
        }

        navigator.geolocation.getCurrentPosition(
            successHandler, 
            errorHandler);

        return () => {}

    }, []);

    return [position, error];
};

Working demo