我正在尝试构建一些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]),它实际上打印了真实的信息,但仍然无法将数组推入状态,并且整个数组都打印为空..
有人见过这种问题吗?
答案 0 :(得分:1)
基于小提琴,看来您不小心在shouldComponentUpdate检查中重置了数组。
shouldComponentUpdate(nextProps, nextState) {
if (nextState.busRealTimeInfo.length = 0 ...
应该是
shouldComponentUpdate(nextProps, nextState) {
if (nextState.busRealTimeInfo.length === 0 ...