【问题标题】:reactJS fetch json data from APIreactJS 从 API 获取 json 数据
【发布时间】:2021-05-22 15:55:26
【问题描述】:

我是 JS 和 reactJS 的新人。 我想从 API 获取信息到数组。我制作了显示数据库中所有信息的 API。 它看起来像这样:

const [tempNew, setTempNew] = useState([]);
const getAllWeatherCelsius = () => {
    fetch('http://localhost:5000/weather')
      .then(response => {
        return response.json();
      })
      .then((jsonData) => {
        let tmpArray = [];
        for (var i = 0; i < jsonData.length; i++) {
          tmpArray.push(jsonData.dayCelsius[i])   <---- here is the error
        }
        setTempNew(tmpArray);
      })
  }

我想将 "dayCelsius" 行中的所有值收集到数组中。
我需要在此代码中更改什么?谢谢你:)

【问题讨论】:

    标签: javascript node.js reactjs api fetch


    【解决方案1】:

    您可以使用map函数返回每个元素的dayCelsius值并将它们存储在tmpArray中。

    let tmpArray = jsonData.map((el, i) => el.dayCelsius);
          
    

    【讨论】:

      【解决方案2】:

      您能否提供有关该错误的更多信息?但是您可以尝试使用地图功能,例如

       const tmpArray = jsonData.map(r => r.dayCelsius);
      

      【讨论】:

        【解决方案3】:

        所以,我的理解是,您很难从 API 获取的对象数组中获取 dayCelsius 值。

        很难确定问题所在,因为需要更多有关错误的信息才能查看问题所在。

        我在这里做的不同的是,我使用了data.map((r,e) =&gt; r.dayCelsius),而不是for循环和jsonData.dayCelsius[i]

        const [temp, setTemp] = useState([]);
        const getAllWeatherCelsius = () => {
            fetch('http://localhost:5000/weather', {
                method: "GET",
                headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json",
                }
            })
              .then(response => {
                return response.json();
              })
              .then((data) => {
                const tempArray = data.map((r,e) => r.dayCelsius); 
                setTemp(tempArray);
              })
              .catch(err => console.log(err));
          }
        

        希望对你有帮助,祝你有个美好的一天:)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-25
          • 2016-11-27
          • 2016-12-25
          • 2018-02-11
          相关资源
          最近更新 更多