【问题标题】:Array undefined outside of javascript function?javascript函数之外的数组未定义?
【发布时间】:2016-05-01 15:15:19
【问题描述】:

我在 React-Native 中定义了一个函数,它从 Firebase 获取一个对象并将其内容推送到一个数组中。然而,虽然在我调用“push”之后数组被很好地填充,但它在 for 循环结束时是未定义的。我不知道为什么要清除它,因为我在 for 循环之外定义数组,所以我想我会要求多一双眼睛,以防我遗漏任何东西。

    var newList = [];
    var arrayLength = userArray.length;
    for (var i = 0; i < arrayLength; i++) {

        var userRef = usersRef.child(userArray[i]);
        userRef.once('value', function(snap) {
            newList.push({
                name: snap.val().name,
                description: snap.val().description,
            });
            //this log statement prints out correct array
            console.log("NEWLIST" + newList[i]);
        });
        //but array is undefined here
        console.log("NEWLIST 2" + newList[i]);
    }
    this.setState({
        current: this.state.current.cloneWithRows(newList),
        past: this.state.past.cloneWithRows(oldList)
    });

【问题讨论】:

标签: javascript arrays firebase react-native undefined


【解决方案1】:

代码看起来不错,但我认为这里可能发生的是 userRef.once() 是一个异步调用,而您的外部 console.log 将首先执行。当事件触发回调时,您的内部 console.log() 会打印该值

【讨论】:

    【解决方案2】:

    阅读 JavaScript 的异步特性。 once 函数接受回调。外部作用域中的 console.log 会在您将任何项目信息推送到您的数组之前执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多