【发布时间】: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。不要使用没有let或const声明的变量。试试let snapshot = await firebase.database().ref(`users/${PersonalId}/chats`).once('value'); for (let i of snapshot.val()) ...
标签: javascript reactjs react-native firebase-realtime-database