【问题标题】:Using information from the first API in the second one - React在第二个 API 中使用来自第一个 API 的信息 - React
【发布时间】:2020-07-18 12:21:50
【问题描述】:

大家!

我有一个小问题。我需要获取两个 API:我需要调用第一个,然后在第二个中使用来自第一个的信息。你能帮我解决一下吗? 这是我当前的代码,但我无法以某种方式获取第一次获取的结果(我可以在控制台和其他东西中看到,所以这不是问题;我只需要从那里获取数据)。

    function App() {
  const [query, setQuery] = useState('');
  const [weather, setWeather] = useState({});


  const search = evt => {
    if (evt.key === "Enter") {
      fetch(`${api.base}forecast?q=${query}&units=metric&APPID=${api.key}`)
        .then(res => res.json())
        .then(result => {
          setWeather(result);
          setQuery('');
          console.log(result);
        })
        .then((result) => {
          const data = fetch(`${api.base}onecall?lat=${result.city.coord.lat}&lon=${result.city.coord.lon}&APPID=${api.key}`)
          console.log(data)
        })
        
    }
  }

【问题讨论】:

    标签: reactjs api fetch


    【解决方案1】:

    您需要在promisethen 中返回结果,因为它会根据返回值创建一个新的承诺。

    const search = evt => {
        if (evt.key === "Enter") {
          fetch(`${api.base}forecast?q=${query}&units=metric&APPID=${api.key}`)
            .then(res => res.json())
            .then(result => {
              setWeather(result);
              setQuery('');
              console.log(result);
              return result; // add return statement 
            })
            .then((result) => {
              const data = fetch(`${api.base}onecall?lat=${result.city.coord.lat}&lon=${result.city.coord.lon}&APPID=${api.key}`)
              data.then((res)=>res.json())
                  .then(result=>{
                      console.log(result)
                   })
            })
            
        }
      }
    

    【讨论】:

    • 嗯,是的 - 我以为是这样,并尝试在之前添加一个 return 语句,但仍然在控制台中获得“promise pending”日志。
    • @MrVoland 在第二个 api 的 console.log 中?它将显示待处理,因为它又是一个承诺,您需要使用 then 来获得结果。我已经更新了我的代码。不过,您可以使用 asyn await 编写更具可读性的代码
    • riiiiiiight,我想我今天太累了 - 明白了,效果很好。感谢朋友的帮助:D
    猜你喜欢
    • 1970-01-01
    • 2022-07-03
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 2019-12-26
    相关资源
    最近更新 更多