【问题标题】:Chain API calls with React hook useEffect链API调用与之反应钩useEffect
【发布时间】:2020-09-18 20:17:31
【问题描述】:

我需要以下序列的解决方案:

浏览器检查用户的地理位置(假设他允许) -> 经度和纬度保持在状态并用于 2 个 API 调用 -> Google Reverse Geolocation API 检查城市名称,同时 DarkSky API 检查天气-> 第三个 API 等待先前调用的结果并将其用作第三个 Unsplash API 的查询

这是我的代码:

const [position, setPosition] = useState({ latitude: '50.049683', longitude: '19.944544' });
const [info, setInfo] = useState({ city: null, weather: null });
const [photos, setPhotos] = useState([]);

useEffect(() => {
    const fetchInfo = async () => {
      try {
        const [cityInfo, weatherInfo] = await Promise.all([
          axios.get(
            `https://maps.googleapis.com/maps/api/geocode/json?latlng=${position.latitude},${position.longitude}&language=en&result_type=locality&key=${GEO_ACC_KEY}`,
          ),
          axios.get(
         `https://api.darksky.net/forecast/${WEATHER_ACC_KEY}/${position.latitude},${position.longitude}?exclude=hourly,daily,alerts,flags`,
          ),
        ]);
        setInfo({
          city: cityInfo.data.results[0].address_components[0].short_name,
          weather: weatherInfo.data.currently.summary.toLowerCase(),
        });

        console.log('Info', info); // Results in {city: null, weather: 'null'}

        const photosData = await axios.get(
          `https://api.unsplash.com/search/photos?query=${info.weather}+${info.city}&page=1&per_page=8&client_id=${UNSPLASH_ACC_KEY}`,
        );

        setPhotos(photosData.data.results);

        console.log('Photos data from API call:', photosData); //Object based on query: "null+null"
        console.log('Photos:', photos); // Empty array
      } catch (err) {
        // Handling errors
      }
    };
    fetchInfo();
  }, []);

  console.log('Info outside axios get', info); // Results in object with city name and current weather
  console.log('photos outside axios get', photos); // Proper result I am looking for

目前,正确的数据仅在 useEffect 之外可用。它不提供第三次 API 调用的数据(现在 Unsplash API 调用使用“null+null”作为查询)。

所以我前往 useEffect 文档,它说第二个参数(一个数组)在任何状态依赖关系发生变化时获取依赖关系和更新。

我尝试如下使用它:

useEffect(() => {
    const fetchInfo = async () => {
      //rest of the code
},
fetchInfo();
}, [info]);

它使用适当的关键字进行 API 调用(城市和天气,而不是 null null)但会创建无限的 API 调用。

我该如何解决这个问题?

【问题讨论】:

    标签: javascript reactjs api react-hooks


    【解决方案1】:

    状态更新不是立即的,将反映在下一个渲染周期中。

    请查看此帖子了解更多详情:useState set method not reflecting change immediately

    您还必须注意,您希望链接 API 调用,而不是在信息更改时再次调用整个 useEffect。添加info作为依赖肯定会导致无限循环,因为info是在useEffect中设置的。

    为了解决您的问题,您可以在进行 api 调用时改用您设置的值

        const newInfo = {
          city: cityInfo.data.results[0].address_components[0].short_name,
          weather: weatherInfo.data.currently.summary.toLowerCase(),
        }
    
         setInfo(newInfo);
    
        console.log('Info', info); // Results in {city: null, weather: 'null'}
    
        const photosData = await axios.get(
          `https://api.unsplash.com/search/photos?query=${newInfo.weather}+${newInfo.city}&page=1&per_page=8&client_id=${UNSPLASH_ACC_KEY}`,
        );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      • 2020-12-20
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      相关资源
      最近更新 更多