我正在尝试从 firebase 获取数据并将数据在循环中一一推送到数组中。但获取的数据数组没有显示在 React 组件上。
我通过控制台登录,发现如下图奇怪的是,console.log(array.length)为0,但console.log(array.length)显示的是数组的内容。
代码如下。
const getThread = (threadID) => {
return db.ref(`threads/${threadID}`).once('value')
.then((snapshot)=>{
return snapshot.val()
})
}
const getThreadList = (id) => {
let threadList = []
return db.ref(`users/${id}/friends`).once('value')
.then((snapshot)=>{
let friends = snapshot.val()
for(let key in friends){
if(friends.hasOwnProperty(key)) {
getThread(friends[key].threadID)
.then((thread)=>{
threadList.push(thread)
})
}
}
return threadList
})
}
class SomeComponent extends Component{
componentDidMount(){
let { id } = this.props
getThreadList(id)
.then(threadList => {
this.setState(() => ({ threadList }))
})
}
render(){
//value of threadList doses't appear
我怀疑这是由于滥用 Promise 造成的,因此 console.log 显示值,但 React 组件没有显示任何内容。但我也怀疑React方面,无法准确定位问题出在哪里。
如果您就这个问题提出任何线索,我们将不胜感激。
最佳答案
您不会等待嵌套的 Promise 得到解决。您可以使用 Promise.all
来完成任务。
const getThreadList = (id) => {
return db.ref(`users/${id}/friends`).once('value')
.then((snapshot)=>{
let friends = snapshot.val()
const threads = []
for(let key in friends){
if(friends.hasOwnProperty(key)) {
threads.push(getThread(friends[key].threadID))
}
}
return Promise.all(threads)
})
}
或者使用Object.values
const getThreadList = id => {
return db
.ref(`users/${id}/friends`)
.once("value")
.then(snapshot => {
const loadingThreads = Object.values(snapshot.val()).map(friend =>
getThread(friend.threadID)
);
return Promise.all(loadingThreads);
});
};
关于javascript - React 不会从 firebase 渲染数组值,并且数组的长度为 0,尽管控制台上有该值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50876402/