如何使用axios.get方法驱动的JSON数据?

时间:2019-01-26 21:11:41

标签: javascript ajax reactjs axios

我正在尝试对从axios.get方法(例如“ console.log(data.results)”)获取的JSON数据中包含的数组使用map方法。当我尝试访问其侧面的数据时,发生以下错误:

TypeError: Cannot read property 'result' of undefined. 

但是,当我放入“ console.log(data)”时,它将记录json数据而没有任何问题。这是我编写的代码,并在数据对象中添加了json数据。

componentDidMount() {
  axios.get('https://api.nytimes.com/svc/topstories/v2/science.json?api-key=privatekey')
      .then(result=>
            this.setState({jsonData:result})
           )
      .catch(error=> console.log(error))
  }
  
  render() {
    return(
      <div id="cards-wrapper">
       {console.log(this.state.jsonData.data)}
      </div>
    )
  }
<!-- console error-->

{status: "OK", copyright: "Copyright (c) 2019 Company. All Rights Reserved.", section: "science", last_updated: "2019-01-26T15:57:14-05:00", num_results: 28, …}
copyright: "Copyright (c) 2019 Company. All Rights Reserved."
last_updated: "2019-01-26T15:57:14-05:00"
num_results: 28
results: (28) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
section: "science"
status: "OK"
__proto__: Object

如何访问数据中的“结果”数组?谢谢你的帮助!

3 个答案:

答案 0 :(得分:1)

您需要确保检查是否设置了jsonData.results.data,否则将因为从一开始就无法使用此数据而引发错误。请记住,您的组件不会等到异步请求首先得到满足,因此,如果您尝试在设置状态之前访问状态内的属性(在这种情况下为数据),则会出错。下面是解决此问题的示例:

class App extends React.Component {
  state = {
    jsonData: null,
  };

  componentDidMount() {
    axios
      .get(
        "https://api.nytimes.com/svc/topstories/v2/science.json?api-key=JoqkiXzZ0GoPgjxFrhHBA42XLzGwAYFq"
      )
      .then(result => this.setState({ jsonData: result }))
      .catch(error => console.log(error));
  }

  render() {
    return (
      <div id="cards-wrapper">
        {this.state.jsonData && this.state.jsonData.data.results.map((article) => (
          <div key={article.short_url}>
            {article.title}
          </div>
        ))}
      </div>
    );
  }
}

就我个人而言,我将状态保持尽可能平坦,并会像下面那样设置数据。这是因为有很多无用的数据,我们可以像版权信息一样将其丢弃。除非您使用此信息,否则我们不需要将其存储在状态以及需要使用的实际数据中。

class App extends React.Component {
  state = {
    jsonData: []
  };

  componentDidMount() {
    axios
      .get(
        "https://api.nytimes.com/svc/topstories/v2/science.json?api-key=JoqkiXzZ0GoPgjxFrhHBA42XLzGwAYFq"
      )
      .then(response => this.setState({ jsonData: response.data.results }))
      .catch(error => console.log(error));
  }

  render() {
    return (
      <div id="cards-wrapper">
        {this.state.jsonData.map(article => (
          <div key={article.short_url}>{article.title}</div>
        ))}
      </div>
    );
  }
}

或者,如果您想保留响应中的所有其他数据,则可以使用loading状态来控制是否应呈现数据。请注意,在axios请求完成之前,我们如何不渲染实际的卡片。这将停止您遇到的原始问题,即正在渲染尚不存在的数据。

class App extends React.Component {
  state = {
    jsonData: [],
    loading: true
  };

  componentDidMount() {
    axios
      .get(
        "https://api.nytimes.com/svc/topstories/v2/science.json?api-key=JoqkiXzZ0GoPgjxFrhHBA42XLzGwAYFq"
      )
      .then(response =>
        this.setState({ loading: false, jsonData: response })
      )
      .catch(error => console.log(error));
  }

  render() {
    return this.state.loading ? (
      <div>loading...</div>
    ) : (
      <div id="cards-wrapper">
        {this.state.jsonData.data.results.map(article => (
          <div key={article.short_url}>{article.title}</div>
        ))}
      </div>
    );
  }
}

答案 1 :(得分:0)

响应返回一个名为results而不是data的数组,因此您不能通过以下方式访问它:

console.log(this.state.jsonData.data)

console.log(this.state.jsonData.results)

答案 2 :(得分:-1)

这仅仅是错字吗?因为它无法读取结果,但可以读取结果。

this.state.jsonData.data.results