开发者问题收集

ReactJS:无法获取 API

2021-08-09
55

嘿,我正在尝试获取一个 API,但它没有返回任何东西。

我已经检查过,我无法访问我获取的预先构建的值。

我如何访问获取中的值?

import React, { useState, useEffect } from 'react';

function App() {
  const [ positionLat, setPositionLat ] = useState('') ;
  const [ positionLong, setPositionLong] = useState('') ;
  
  navigator.geolocation.getCurrentPosition(function(position) {
    setPositionLat(position.coords.latitude);
    setPositionLong(position.coords.longitude);
  });

console.log(positionLat) // returns good result
console.log(positionLong) // returns good result

// I obviously need to call those values inside my fetch

useEffect(() => {
  console.log(positionLat) // returns undefined
  console.log(positionLong) // returns undefined
  fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${positionLat}&lon=${positionLong}&appid={api_key}b&units=metric`)
   .then(res => {
    return res.json();
   })
   .then(data => {
    console.log(data)
   })
}, []);

  return (
    <div className="App">
      <p>lattitude :{positionLat}</p>
      <p>longitude :{positionLong}</p>
    </div>
  );
}

export default App;
1个回答

一种选择是将您的效果挂钩更改为仅在定义值后运行主体:

useEffect(() => {
  if (positionLat === '' || positionLong === '') {
    return;
  }
  // rest of function
  fetch(...
}, [positionLat, positionLong]);

您还需要修复您的地理位置调用,使其仅在挂载时发生一次。

useEffect(() => {
  navigator.geolocation.getCurrentPosition(function(position) {
    setPositionLat(position.coords.latitude);
    setPositionLong(position.coords.longitude);
  });
}, []);

另一种选择是将其拆分为两个组件,并且仅在地理位置调用完成后渲染子组件(执行提取操作),这可能看起来更干净。

const App = () => {
    const [coords, setCoords] = useState();
    useEffect(() => {
        navigator.geolocation.getCurrentPosition(function (position) {
            setCoords(position.coords);
        });
    }, []);
    return coords && <Child {...coords} />;
};
const Child = ({ latitude, longitude }) => {
    useEffect(() => {
        fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid={api_key}b&units=metric`)
            .then(res => res.json())
            .then(data => {
                // do stuff with data
            })
            // .catch(handleErrors); // don't forget to catch errors
    }, []);
    return (
        <div className="App">
            <p>latitude :{latitude}</p>
            <p>longitude :{longitude}</p>
        </div>
    );
};
CertainPerformance
2021-08-09