简体   繁体   English

将对象推送到无法使用Javascript的数组反应

[英]push an object to an array not working on Javascript react

I'm trying to build some react app, and in that app Im pushing some objects to an array, then setting this arrray as a react component state. 我正在尝试构建一些react应用程序,并在该应用程序中将某些对象推入数组,然后将该错误设置为react组件状态。 The problem is that's not working, this is my code - 问题是那不起作用,这是我的代码-

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))

as you see I try to write the final array to the console to see the result, and I see this strange array that has a length but empty inside - 如您所见,我尝试将最终数组写入控制台以查看结果,并且我看到了这个奇怪的数组,它的长度却是空的-

在此处输入图片说明

does anyone know what is this? 有人知道这是什么吗? and why it is happening? 以及为什么会这样?

UPDATE I tried to change the console.log(busArray) to console.log(busArray[0]) and it actually printed the real inforamtion, but still can't push the array into the state and the whole array printed to the console as empty.. 更新我试图将console.log(busArray)更改为console.log(busArray [0]),它实际上打印了真实的信息,但仍然无法将数组推入状态,并且整个数组都按如下方式打印到控制台空.. 在此处输入图片说明

somebody ever saw that kind of problem? 有人见过那种问题吗?

Based on the fiddle, it looks like you are accidentally resetting the array in the shouldComponentUpdate check. 基于小提琴,看来您不小心在shouldComponentUpdate检查中重置了数组。

 shouldComponentUpdate(nextProps, nextState) {
        if (nextState.busRealTimeInfo.length = 0 ...

Should be 应该

shouldComponentUpdate(nextProps, nextState) {
            if (nextState.busRealTimeInfo.length === 0 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM