我正在尝试构建一些 react 应用程序,并在该应用程序中将一些对象推送到数组,然后将此数组设置为 react 组件状态。 问题是这不起作用,这是我的代码 -
var busArray = []
if(apiResponse.length > 0)
{
for(var i in apiResponse) {
if("ns3:VehicleLocation" in apiResponse[i]["ns3:MonitoredVehicleJourney"][0]) {
var busInfoObject = {"lineNo": apiResponse[i]["ns3:MonitoredVehicleJourney"][0]["ns3:PublishedLineName"][0],
"operatorCode": apiResponse[i]["ns3:MonitoredVehicleJourney"][0]["ns3:OperatorRef"][0],
"lat": apiResponse[i]["ns3:MonitoredVehicleJourney"][0]["ns3:VehicleLocation"][0]["ns3:Latitude"][0],
"lng": apiResponse[i]["ns3:MonitoredVehicleJourney"][0]["ns3:VehicleLocation"][0]["ns3:Longitude"][0]
}
busArray.push(busInfoObject)
}
}
}
else {
console.log("No busses nearby detected")
}
console.log(busArray)
this.setState({busRealTimeInfo: busArray}, ()=> console.log(this.state.busRealTimeInfo))
如您所见,我尝试将最终数组写入控制台以查看结果,我看到这个奇怪的数组,它有长度但内部为空 -
有人知道这是什么吗?以及为什么会发生这种情况?
更新 我尝试将 console.log(busArray) 更改为 console.log(busArray[0]) ,它实际上打印了真实的信息,但仍然无法将数组插入状态并将整个数组作为空打印到控制台..
有人见过这样的问题吗?
最佳答案
根据 fiddle ,看起来您不小心在 shouldComponentUpdate 检查中重置了数组。
shouldComponentUpdate(nextProps, nextState) {
if (nextState.busRealTimeInfo.length = 0 ...
应该是
shouldComponentUpdate(nextProps, nextState) {
if (nextState.busRealTimeInfo.length === 0 ...
关于javascript - 将对象推送到数组不适用于 JavaScript react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52444267/