[英]push an object to an array not working on Javascript react
我正在嘗試構建一些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]),它實際上打印了真實的信息,但仍然無法將數組推入狀態,並且整個數組都按如下方式打印到控制台空..
有人見過那種問題嗎?
基於小提琴,看來您不小心在shouldComponentUpdate檢查中重置了數組。
shouldComponentUpdate(nextProps, nextState) {
if (nextState.busRealTimeInfo.length = 0 ...
應該
shouldComponentUpdate(nextProps, nextState) {
if (nextState.busRealTimeInfo.length === 0 ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.