我正在尝试从火车中获取值,例如 id 和 number,但是当我尝试这样做时,没有显示任何值。当我尝试 console.log 时,我得到未定义的响应。它适用于station.name 和station.city,但我不适用于station.trains.is。 这是我的代码:
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>
);
}
}
这是我从 API 得到的响应:
答案 0 :(得分:2)
trains 是数组,您可以使用 Map
或 foreach
station.train.map(item=>item.id)