所以我在容器组件中有这个方法:
getProfilesOptions = () => {
const result = firebase.firestore().collection('roles').get().then(snapshot => {
const options = []
snapshot.docs.forEach(doc => {
options.push({ value: doc.id, label: doc.data().profile })
//console.log(doc.id) - everything ok, i'm fetching data correctyly
});
return options
})
console.log(result)//here i have pending result in debugger
return result
}
然后,我将链接传递到子...子...子组件。
然后我想调用它,并获取数组作为结果,然后设置状态:
componentDidUpdate() {
if(this.state.isFocused && !this.state.options){
const options = this.props.getOptions()
this.setState({
options: options
})
}
}
我可以解决这个问题吗?当然,我可以将 props 作为结果而不是 props 引用传递给该方法,但是我可以使用该方法吗?如何改进getProfilesOptions?
最佳答案
您应该将 firebase 调用包装在 Promise 中,因为这是一个异步调用。
getProfilesOptions = () => {
return new Promise(resolve => {
firebase.firestore().collection('roles').get().then(snapshot => {
const options = []
snapshot.docs.forEach(doc => {
options.push({ value: doc.id, label: doc.data().profile })
//console.log(doc.id) - everything ok, i'm fetching data correctyly
});
resolve(options)
})
}
}
并使用 .then() 在组件中获取结果
componentDidUpdate() {
if(this.state.isFocused && !this.state.options){
this.props.getOptions().then(options => {
this.setState({
options: options
})
})
}
}
您可以阅读有关 Javascript Promises 的更多信息 here
关于javascript - 如何在方法中等待firebase、获取数据并返回数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56045073/