Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

javascript - Get values from array of JSONs in JSON ReactJS

I'm trying to get values from JSON that looks like this:

{
    "id": 371,
    "city": "London",
    "name": "London Station",
    "trains": [
        {
            "id": 375,
            "number": "1023",
            "numberOfCarriages": "21"
        }
    ]
}

I want to get values from trains, like number and numberOfCarriages. I'm trying to get those values in React. My React code:

class ViewTrainsComponent extends Component {
    constructor(props) {
        super(props)

        this.state = {
            id: this.props.match.params.id,
            station: []
        }
    }


    render() {
        return (
            <div>
                        <div className="row">
                            {/* <div>{this.state.station[0].trains[0].number}</div> */}
                        </div>
            </div>
        );
    }
}

Am I doing it right? How can I get those values in render function?

EDIT.

Here is the response from API enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Avoid setting and updating state directly with

this.state = ...

except when you are initializing it in the constructor. Instead, use either setState() function or the useState hook.

But I think your question is more about how to get the values of the trains in render function, You can access those as

render() {
    return <div>{this.state.stations[i].trains[j].number}</div>
  }

so for the first train of first station i=0 and j=0 and for the second train in first station i=0 and j=1. for the first train of second station i=1 and j=0 and for the second train in first station i=1 and j=1.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...