【问题标题】:Value from response is undefined ReactJs来自响应的值是未定义的 ReactJs
【发布时间】:2021-01-09 13:55:47
【问题描述】:

我正在尝试从火车中获取值,例如 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 得到的响应:

【问题讨论】:

    标签: javascript reactjs api


    【解决方案1】:

    trains 是数组,您可以使用Mapforeach 访问其成员

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

    【讨论】:

    • 或 trains.map({id}=>id)
    猜你喜欢
    • 2020-04-08
    • 1970-01-01
    • 2021-03-19
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多