【问题标题】:ReferenceError: Can't find variable: i (for-loop problem)ReferenceError:找不到变量:i(for循环问题)
【发布时间】:2021-07-14 22:00:23
【问题描述】:

我从我的 react native 项目中休息了大约 3 周,现在我回来并想继续工作,不幸的是,该应用程序甚至没有渲染第一个屏幕组件。我已经弄清楚问题是什么了,我只是完全混淆了发生了什么:

    var chatkeys = [];
    var partnerkeys = [];
    var contactsDATA = [];

    await firebase.database().
    ref(`users/${PersonalId}/chats`).
    once('value').
    then(snapshot =>{
        for (i in snapshot.val()){//pulling all chatcodes out of database and pushing into chatkeys
            chatkeys.push(snapshot.val()[i]);
        };
    });

问题出在for循环中。这是我收到的错误:

[未处理的承诺拒绝:ReferenceError:找不到变量:i]

  • node_modules\react-native\node_modules\promise\setimmediate\core.js:37:13 在 tryCallOne 中
  • node_modules\react-native\node_modules\promise\setimmediate\core.js:123:24 in setImmediate$argument_0
  • node_modules\react-native\Libraries\Core\Timers\JSTimers.js:130:14 in _callTimer
  • node_modules\react-native\Libraries\Core\Timers\JSTimers.js:181:14 in _callImmediatesPass
  • node_modules\react-native\Libraries\Core\Timers\JSTimers.js:441:30 in callImmediates
  • node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:387:6 在 __callImmedates
  • node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:135:6 在 __guard$argument_0
  • node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 在 __guard
  • node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:134:4 在flushedQueue中
  • [本机代码]:flushedQueue 中为空
  • [native code]:null in callFunctionReturnFlushedQueue

JS怎么找不到变量“i”?我从来没有告诉 JS 搜索“i”——它应该是一个循环遍历整个 snapshot.val() 数组的计数器。这是怎么回事?

【问题讨论】:

  • 您是否尝试过声明它,例如for (let i in ...)? (我一般也不会使用var。)
  • 混合await.then 是一种反模式。使用for..of 而不是for..in。不要使用没有letconst 声明的变量。试试let snapshot = await firebase.database().ref(`users/${PersonalId}/chats`).once('value'); for (let i of snapshot.val()) ...

标签: javascript reactjs react-native firebase-realtime-database


【解决方案1】:

错误指出i 未定义。阅读您的代码,我可以看到您的 for 循环声明中的 i 可能缺少 let i 变量。

你试过for (let i in snapshot.val()){

【讨论】:

    【解决方案2】:

    i 未在范围内声明。 试试

    for (let i in snapshot.val()){//pulling all chatcodes out of database and pushing into chatkeys
                chatkeys.push(snapshot.val()[i]);
            };
    

    let i;
    for (i in snapshot.val()){//pulling all chatcodes out of database and pushing into chatkeys
                chatkeys.push(snapshot.val()[i]);
            };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-14
      • 1970-01-01
      • 2012-06-08
      • 1970-01-01
      • 1970-01-01
      • 2014-02-20
      • 2018-04-24
      • 1970-01-01
      相关资源
      最近更新 更多