简体   繁体   中英

Unable to access element from array of JSON objects

I am trying to access the specific elements of an array of JSON objects. To test I simply have:

{console.log(this.state.stockCharts)}

This returns (in browser):

返回JSON

This is great, but now I want to access a specific element. Say the first element. I type:

{console.log(this.state.stockCharts[0])}

And the browser is like: nah mate

undefined

It's probably something really simple, but I have been banging my head against my keyboard for the past 45 minutes and nothing has worked. Thanks guys!

Edit 1 (For Akrion)

The query that I am using to access the API is:

https://www.alphavantage.co/query?function=TIME_SERIES_WEEKLY&symbol=MSFT&apikey=demo

This is what I get back from the call:

调用Alpha Advantage API

I call this API twice, and after I get a response back I push it to my stockCharts array:

this.state.stockCharts.push(result)

Edit 2 (For Beginner)

I initialize the state how you would normally do it:

this.state = {
        stockCharts: []
}

I verified with the api given in my local and I am able to get the data.

First thing the way you push api response to stockCharts is not recommended. Which means direct mutation of the state is not recommended.

You can push api response in the following way

this.setState(prevState => ({
   stockCharts: [...prevState.stockCharts, result]
}));

Now in render

render(){
   this.state.stockCharts.map((data, i) => {
      console.log("data", data); // this will give each object
      console.log("Meta Data", data["Meta Data"]); //This will give meta data information
      console.log("Weekly Time Series", data["Weekly Time Series"]);// this will print weekly time information
   });
   return(

   )
}

Is this what your expectation?

It might be because you mutate the state which is not recommended. try instead of calling this.state.stockCharts.push(result) do this.setState({stockCharts: [...this.state.stockCharts, result]})

https://reactjs.org/docs/state-and-lifecycle.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM