TL; DR:,我的目标是分离 API函数,并在需要时将其导入。然后在componentDidMount
情况下呼叫他们。另外,有人告诉我async
和await
将与之一起使用,因为:getCurrentPosition
是一个异步函数。
答案 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)
解决问题所需的所有提示均在错误代码中
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];
};