【问题标题】:React js console array element undefindReact js控制台数组元素未定义
【发布时间】:2018-01-20 20:58:52
【问题描述】:

我试着打印一下

console.log(location_list.all_list[3]);
console.log(location_list.all_list);

但在 1 种情况下有“未定义”。 哪里不对?

更多代码:

    var items = [];
    
    $.getJSON( "js/location_list.json", function( data ) {
        $.each( data, function( key, val ) {
            items.push(key=val);
        });
    });
    
    this.all_list = items;

结论: 此类赋值不能在“getJSON”中使用

this.all_list = items;

【问题讨论】:

  • location_list 的值是多少?
  • console.log(typeof location_list); // 对象
  • 您只提供了 2 行代码并询问发生了什么,我们几乎没有回答
  • 不,是 115、116 和 117 行

标签: json reactjs getjson


【解决方案1】:

我给你思路

使用回调技术

更改list_load的定义,添加cb

list_load : function(cb){
    var self = this;
    self.all_list = [];
    $.getJSON( "js/location_list.json", function( data ) {
        $.each( data, function( key, val ) {
            self.all_list.push(key=val);
        });
        cb()
    });
},

然后

location_list.list_load(function(){
    console.log(location_list.all_list[3]);
    console.log(location_list.all_list);
    console.log(typeof location_list);
});

【讨论】:

  • 如何在没有拐杖的情况下正确地做?这可能吗?
  • ajax需要处理异步,回调技术是更好的方法
  • 还有 1 个问题。为什么在 getJSON 中这样做是错误的? this.all_list.push(val);谢谢!
  • 好的,我为你更新了list_load,你应该从this - JavaScript | MDN了解更多关于函数的this,你不能直接在回调函数中使用this
【解决方案2】:

基于此代码:

    var items = [];
    $.getJSON( "js/location_list.json", function( data ) {
        $.each( data, function( key, val ) {
            items.push(key=val);
        });
    });
    this.all_list = items;

看起来是因为异步

检索事件中的语句

$.each( data, function( key, val ) {
    items.push(key=val);
});

您在检索事件发生之前致电console.log(location_list.all_list[3]);

console.log(location_list.all_list); => []
console.log(location_list.all_list[3]); => 'undefined'

你需要检查all_list的长度

if(location_list.all_list.length > 3) console.log(location_list.all_list[3]);

【讨论】:

  • 比较棘手的是,当打印all_list时,Chrome会在加载内容时改变打印的值。
  • 但是在控制台输出长度:8,为什么?
  • @МаргаритаКорнилова 您在请求实际发生之前分配this.all_list = items;,您应该在$.getJSON 的完成处理程序中进行分配。实际发生的情况是您分配一个空数组,然后打印空值,然后您的请求发生并填充数组,然后 Chrome 使用当前值更新您之前的控制台日志 all_list
猜你喜欢
  • 2021-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-18
  • 1970-01-01
  • 2023-03-31
  • 2021-05-05
  • 1970-01-01
相关资源
最近更新 更多