简体   繁体   English

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

[英]How can I use JSON data driven from axios.get method?

I am trying to use map method on the array included in JSON data I got from axios.get method such as 'console.log(data.results)'. 我试图在从axios.get方法(例如“ console.log(data.results)”)获取的JSON数据中包含的数组上使用map方法。 when I try to access to the data in side of it, following error occurs: 当我尝试访问其侧面的数据时,发生以下错误:

TypeError: Cannot read property 'result' of undefined. 

When I put 'console.log(data)', however, it logs the json data without any problems. 但是,当我放入“ console.log(data)”时,它将记录json数据而没有任何问题。 This is the code I wrote and json data in data object. 这是我编写的代码和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 

How can I access to the 'results' array in the data? 如何访问数据中的“结果”数组? thank you for help! 谢谢你的帮助!

You need to ensure that you check if jsonData.results.data has been set or else it'll throw an error since this data isn't available from the start. 您需要确保检查是否已设置jsonData.results.data,否则将引发错误,因为从一开始就无法使用此数据。 Remember that your component does not wait till the async request has fulfilled first, so if you are trying to access a property (in this scenario the data) inside the state before it is set, then it will error out. 请记住,您的组件不会等到异步请求首先得到满足,因此,如果您尝试在设置状态之前访问状态内的属性(在这种情况下为数据),则会出错。 Here's an example below to fix the issue: 以下是解决此问题的示例:

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>
    );
  }
}

Personally, I'd keep the state as flat as possible and would go about setting data like below. 就个人而言,我将状态保持尽可能平坦,并会像下面那样设置数据。 This is because there is a lot of useless data that we can just discard like copyright information. 这是因为有很多无用的数据,我们可以像版权信息一样将其丢弃。 Unless you use this information, we don't need to store it in the state as well as the actual data we need to use. 除非您使用此信息,否则我们不需要将其存储在状态以及需要使用的实际数据中。

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>
    );
  }
}

Or if you want to keep all the other data from the response you can use a loading state that controls if the data should be rendered. 或者,如果要保留响应中的所有其他数据,则可以使用loading状态来控制是否应呈现数据。 Notice how we don't render the actual card until the axios request has fulfilled. 请注意,在axios请求完成之前,我们如何不渲染实际的卡片。 This will stop the original issue you're running into where you are rendering data that doesn't exist yet. 这将停止您遇到的原始问题,即正在渲染尚不存在的数据。

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>
    );
  }
}

The response returns an array named results , not data so you access it not with: 响应返回一个名为results而不是data的数组,因此您不能通过以下方式访问它:

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

but with 但随着

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

is it simply a typo? 这仅仅是错字吗? since it cant read result, but its results. 由于它无法读取结果,但其结果。

this.state.jsonData.data.results

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 axios.get 呈现数据 - How can i render data using axios.get 如何在 react-redux 中的 axios.get 方法中传递登录用户的 ID? - How can I pass the ID of logged-in user in the axios.get method in react-redux? 如何将请求数据从axios.get获取到Redux存储 - How to get request data from axios.get to Redux store axios.get不返回JSON - axios.get not returning JSON 将GET请求数据加载到DataTable中(从本地JSON切换到axios.get) - Loading GET request data into a DataTable (switching from local JSON to axios.get) 如何使用 axios 从 json 获取数据? (反应) - How can I get data from json with axios? (React) 我可以使用 TypeScript 在 axios.get 方法中指定泛型类型的任何类型 - any type of I can designate in generic types in axios.get method with TypeScript Axios.get 返回普通 html 而不是 JSON 返回数据 - Axios.get returns plain html intead of JSON return data axios拦截器处理程序如何在其创建方法正在调用axios.get的内部访问vue组件实例(此指针)? - how can axios interceptor handler get access to vue component instance(this pointer)within whose created method is invoking axios.get? 当我想从 Json 数据或 API 与 axios.get 获取或获取某些特定字段时,response.data.key 返回未定义 - response.data.key return undefined when i want to grab or get some specific fields from Json data or API with axios.get
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM