如何从 this.state 中获取值。 属性 个未定义

How to get value from this.state. Property of undefined

我正在尝试将值从一个组件传递到另一个组件。第一个看起来像这样:

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

        this.state = {
            stations: []
        }

        this.editStation = this.editStation.bind(this);
    }


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

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

    }

    render() {
        return (
            <div>

                        <tbody>
                            {this.state.stations.map(
                                station =>
                                    <tr key={station.id}>
                                        <td>{station.city}</td>
                                        <td>{station.name}</td>
                                        <td>
                                            <button onClick={() => this.editStation(station.id)} className="btn btn-info">Modify</button>
                          ...                  
                </div>
            </div>
        );
    }
}

export default ListStation;

另一个看起来像这样:

import React, { Component } from 'react';
import StationService from '../services/StationService';

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

        this.state = {
            station: {
                id: this.props.match.params.id,
                city: '',
                name: '',
                trains: [
                    {
                        number: '',
                        numberOfCarriages: ''
                    }
                ]
            }
        }

        this.changeCityHandles = this.changeCityHandles.bind(this);
        this.changeNameHandles = this.changeNameHandles.bind(this);
        this.saveStation = this.saveStation.bind(this);
    }

    componentDidMount() {

        if (this.state.station[0].id === '_add') {
            return;
        } else {
            StationService.getStationById(this.state.id).then((res) => {
                let station = res.data;
                this.setState({ name: station[0].name, city: station[0].city })
            });
        }
        console.log(this.state.station.city + 'dfddddd');
    }

但是当我尝试将值从一个组件传递到另一个组件时,出现错误:属性 of undefined。我从 API 得到的响应如下所示:

我正在尝试根据从第一个组件获取的 ID 编辑值,但它似乎失败了。

改为if (this.state.station.id === '_add') {

if (this.state.station[0].id === '_add') {
        return;
    } 

看看代码库中的这个 if 语句我认为你应该在 this.state.station 之后删除 [0] ...这是因为站是一个对象而不是数组