【问题标题】:Using multiple axios get requests inside useEffect yields undefined values在 useEffect 中使用多个 axios get 请求会产生未定义的值
【发布时间】:2022-11-11 20:48:33
【问题描述】:

作为一个整体,我对 React 和 Web 开发非常陌生,我知道代码的样式非常糟糕,但请多多包涵。

我正在尝试使用 openweathermap API 获取天气数据,我必须将纬度和经度用于我想要的位置,当我向它提供一个国家的首都和国家代码时,我应该从他们单独的地理编码 API 中获取我'我感兴趣。

我有点不确定如何“堆叠”这些请求,以便第一个坐标请求通过并将坐标提供给第二个天气请求。我的问题是坐标(否则我会成功)在我的下一个请求中未定义,我不知道为什么,我已经尝试了很多。

const Content = ({result}) => {
  const languages = [result['languages']]
  const [weather, setWeather] = useState([])
  const [coordinate, setCoordinates] = useState([])
  const api_key = process.env.REACT_APP_API_KEY

  useEffect(() => {
    axios
        .get(`http://api.openweathermap.org/geo/1.0/direct?q=${result['capital']},${result['cca2']}&limit=1&appid=${api_key}`)
        .then(response => {
          setCoordinates(response.data)
        })
        .then(() =>
            axios
                .get(`https://api.openweathermap.org/data/3.0/onecall?lat=${coordinate['lat']}&lon=${coordinate['lon']}&exclude=1&appid=${api_key}`)
                .then(response => {
                  setWeather(response.data)
            }))
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

【问题讨论】:

    标签: reactjs react-hooks axios


    【解决方案1】:

    setCoordinates 不会立即更新 coordinate,因为 React 会批量更新状态。因此,状态是异步更新的。

    如果您的第二个请求依赖于 coordinate 数组的状态更改,那么您应该将其移动到自己的 useEffect 挂钩中:

    const Content = ({result}) => {
      const languages = [result['languages']]
      const [weather, setWeather] = useState([])
      const [coordinate, setCoordinates] = useState([])
      const api_key = process.env.REACT_APP_API_KEY
    
      useEffect(() => {
        axios
            .get(`http://api.openweathermap.org/geo/1.0/direct?q=${result['capital']},${result['cca2']}&limit=1&appid=${api_key}`)
            .then(response => {
                setCoordinates(response.data)
            });
      }, []);
    
      // Your second API call is dependent on state changes to `coordinate`
      useEffect(() => {
        axios
            .get(`https://api.openweathermap.org/data/3.0/onecall?lat=${coordinate['lat']}&lon=${coordinate['lon']}&exclude=1&appid=${api_key}`)
            .then(response => {
                setWeather(response.data)
            });
      }, [coordinate]);
    };
    

    【讨论】:

      猜你喜欢
      • 2020-07-30
      • 1970-01-01
      • 2021-06-04
      • 2020-08-23
      • 2021-03-21
      • 2020-09-08
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      相关资源
      最近更新 更多