javascript - 无法读取未定义 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>
);
}
}
解决方案
改成:
render() {
return (
<div>
<div>{this.state.station?.name}</div>
<h1>{this.state.station?.trains[0]?.number}}</h1>
</div>
);
}
推荐阅读
- racket - 映射到嵌套列表,函数应用于引用
- plot - 多图中每个图的标题
- git - 为什么“git submodule update”会跳过子模块?
- delphi - 如何刷新 TListView 和 TFDMemTable 的 Livebinding?
- c# - C# Selenium SendKeys 即使使用 Javascript 执行程序也无法正常工作
- java - MultiThread_Unable 得到预期的输出
- python - Excel 添加@ 运算符并给出#NAME?错误
- python - 如何将我的 for 循环转换为字典理解?
- java - Resteasy 应用程序总是返回 404
- c++ - 在 if/else if 分支之后使用未声明的标识符