首页 > 解决方案 > 无法读取未定义 ReacJS 的属性“编号”

问题描述

我使用 ReactJS 作为我的应用程序的前端。我从 API 获取值,但是当我尝试获取它们时出现错误“无法读取未定义的属性编号”。这是我的代码:

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

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

    componentDidMount() {
        StationService.getStationById(this.state.id).then(res => {
            this.setState({ station: res.data });
            console.log(res.data);
        })
    }

    render() {
        return (
            <div>
                <div>{this.state.station.name}</div>
                <h1>{this.state.station.trains.number}}</h1>
            </div>
        );
    }
}

这是响应,我尝试获得的值是 number 和 numberOfCarriages。 在此处输入图像描述

标签: javascriptreactjsapiresponse

解决方案


改成:

render() {
    return (
        <div>
            <div>{this.state.station?.name}</div>
            <h1>{this.state.station?.trains[0]?.number}}</h1>
        </div>
    );
}

推荐阅读