React钩子-从api获取数据并传递给组件

时间:2020-05-31 20:58:19

标签: reactjs react-hooks

因此,基本上,我试图从api获取数据并将其传递给Component。

我创建usePosition挂钩以从浏览器获取我的位置,然后从api获取响应。我真的不知道该如何等待useEffect来等待我的位置,当我现在执行此代码时,我总是会遇到“无位置”的记录。

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

  useEffect(() => {
    const geo = navigator.geolocation;
        if(!geo) {
            setError('Geolocation is not supported.');
            return;
        }

        const handleSuccess = position => {
            const { latitude, longitude } = position.coords;
            setPosition({
                latitude,
                longitude
            });
        };

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

        geo.getCurrentPosition(handleSuccess, handleError);

    }, []);

    return { position, error };
}


function App() {
  const {position, error} = usePositon();
  const [weather, setWeather] = useState([]);

  useEffect(() => {
    if(position) {
      const URL = `https://api.openweathermap.org/data/2.5/onecall?lat=${position.latitude}&lon=${position.longitude}&exclude=current,minutely,daily&units=metric&lang=pl&appid=${API_KEY}`;

      const fetchData = async () => {
        const result = await fetch(URL)
          .then(res => res.json())
          .then(data => data);
        setWeather(result.hourly);  
      }
      fetchData();
    } else {
      console.log('no position');
    }
  }, []);

  return (
      <div className="App">
        <div>
          <Swiper weather={weather}/>
        </div>
      </div>
    )
}

1 个答案:

答案 0 :(得分:0)

这是因为[]的{​​{1}}中有App个空的依赖项列表。当useEffect尚未请求任何内容时,它仅在安装时运行一次。并且一旦成功以后又返回不同的usePosition,应用程序将不响应。

如何解决?提供相关性:

{ error, position }