【问题标题】:JSON array of Objects not accessible by index, only by 'response.data'JSON 对象数组无法通过索引访问,只能通过“response.data”访问
【发布时间】:2021-06-24 20:23:48
【问题描述】:

我正在尝试解析 JSON 数组:

{
   "data":[
      {
         "dates":"02/01/2021-02/14/2021",
         "profit":23002,"revenue":230
      },...
   ]
}

我希望将此解析的 JSON 对象作为数据传递到图表中,但是当我 console.log 返回 res.data 的函数时,它被读取为 undefined。在下面的代码中,第一个控制台日志给了我数据,但第二个是未定义的。任何方向都会有所帮助。

const getData = () => {
    axios.get(`https hidden for privacy reasons`)
      .then(res => {
        console.log(res.data)
        return res.data
      })

      .catch((error) => {
        console.log("Ran into error");
      })
  }


console.log(getData())

【问题讨论】:

    标签: javascript json axios recharts


    【解决方案1】:

    axios.get 是一个带有回调的异步函数。这种类型的函数不返回数据 - 相反,数据只能在提供的回调函数的范围内访问,即在

    res => {
            console.log(res.data)
            return res.data
          }
    

    匿名函数。

    请注意,您的 getData 函数不包含 return 语句,因此将返回 undefined 值。

    【讨论】:

      【解决方案2】:

      你想让getData返回Axios get的结果:

      const getData = () => {
          return axios.get(`https hidden for privacy reasons`)
            .then(res => {
              console.log(res.data)
              return res.data
            })
      
            .catch((error) => {
              console.log("Ran into error");
            })
        }
      

      然后你需要Promise.then(或await)结果,因为getData是一个承诺:

        getData().then(result => {
          console.log(result);
        });
      

      【讨论】:

        猜你喜欢
        • 2019-01-11
        • 1970-01-01
        • 1970-01-01
        • 2020-07-19
        • 1970-01-01
        • 2012-02-28
        • 2021-09-12
        • 1970-01-01
        • 2016-04-01
        相关资源
        最近更新 更多