我正在构建一个使用 REST API 的小型应用程序。我在显示对象数组内的信息时遇到问题,请参阅下面的代码:
actions.js
import axios from 'axios'
function fetchService () {
return axios.get('http://localhost:5000/ldbws-rest-proxy/v0.1/departure-board/IPS')
.then(function (response) {
return {
service: response.data.trainServices[0]
}
})
.catch(function (response) {
console.log(response)
})
}
export default fetchService
train_service.js
import fetchService from '../actions'
import DepartureTime from './departure_time'
import OriginStation from './origin_station'
var TrainService = React.createClass ({
getInitialState () {
return {
service: []
}
},
componentDidMount () {
fetchService()
.then(function (dataObj) {
this.setState({
service: dataObj.service
})
}.bind(this))
},
render () {
return (
<section>
<DepartureTime time={this.state.service.std} />
<OriginStation name={this.state.service.origin[0].crs} />
</section>
)
}
})
export default TrainService
JSON 示例 (response.data.trainServices[0])
{
"destination": [
{
"crs": "CBG",
"locationName": "Cambridge"
}
],
"etd": "On time",
"operator": "Greater Anglia",
"operatorCode": "LE",
"origin": [
{
"crs": "IPS",
"locationName": "Ipswich"
}
],
"serviceID": "ILZn7gyLj+eoZZfyaFlP0w==",
"std": "12:20"
}
问题是 <OriginStation name={this.state.service.origin[0].crs} />
抛出错误:
TypeError: undefined is not an object (evaluating 'this.state.service.origin')
我不知道为什么这不起作用,如果我这样做的话console.log(dataObj.service.origin[0].crs)
在 componentDidMount 内部它输出良好。我认为这与原始数组有关......
感谢任何帮助。
编辑:
Chrome 检查器中的状态屏幕截图:
最佳答案
这是因为您的 TrainService
渲染方法调用早于 fetchService
promise 解析。
修复错误的最简单方法是等待 fetchService
更新 service
状态:
var TrainService = React.createClass ({
getInitialState () {
return {
service: null
}
},
componentDidMount () {
fetchService()
.then(function (dataObj) {
this.setState({
service: dataObj.service
})
}.bind(this))
},
render () {
if (this.state.service === null)
return null;
return (
<section>
<DepartureTime time={this.state.service.std} />
<OriginStation name={this.state.service.origin[0].crs} />
</section>
)
}
})
关于javascript - 在 React 中使用对象数组作为 props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41979368/