Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Value from response is undefined ReactJs

I'm trying to get values from trains such as id and number, but when I try to do that, no values shows. When I try to console.log that I get response of undefined. It works well with station.name and station.city but i does not work with station.trains.is. Here is my code:

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

        this.state = {
            stations: []
        }

        this.addStation = this.addStation.bind(this);
        this.editStation = this.editStation.bind(this);
        this.deleteStation = this.deleteStation.bind(this);
        this.showTrains = this.showTrains.bind(this);
    }

    deleteStation(id) {
        StationService.deleteStation(id).then(res => {
            this.setState({ stations: this.state.stations.filter(station => station.id !== id) });
        })
    }

    editStation(id) {
        this.props.history.push(`/add-station/${id}`);
    }

    componentDidMount() {
        StationService.getStations().then((res) => {
            this.setState({ stations: res.data });
        })
    }

    addStation() {
        this.props.history.push('/add-station/_add');
    }

    showTrains() {
        this.props.history.push('/show-train');
    }

    render() {
        return (
            <div>
                <div className="row">
                    <table className="table table-striped table-bordered">

                        <tbody>
                            {this.state.stations.map(
                                station =>
                                    <tr key={station.id}>
                                        <td>{station.city}</td>
                                        <td>{station.name}</td>
                                        <td>{station.trains.id}</td>
                                        {/* {console.log(station.trains.id)} */}
                                        {console.log(station.name)}

                            )}

                        </tbody>
                    </table>
                </div>
            </div>
        );
    }
}

And here is the response I get from API:

enter image description here

question from:https://stackoverflow.com/questions/65643456/value-from-response-is-undefined-reactjs

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

1 Answer

0 votes
by (71.8m points)

trains is array And you can access its members with Map or foreach

station.train.map(item=>item.id)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...