【发布时间】:2020-11-20 23:10:14
【问题描述】:
我很确定问题出在异步行为上。我认为这是因为我的反应应用程序在userLinks.exists 为真时有条件地呈现,但这只有在 firebase 方法完成后才会被分配。关于如何解决这个问题的任何建议?页面一直呈现空白屏幕并出现错误:
react-dom.development.js:13413
Uncaught Error: Objects are not valid as a React child (found: [object Promise]).
If you meant to render a collection of children, use an array instead.
app.js
const User = async ({ match, location }) => {
const userLinks = await firebase.getUserInfo(match.params.user)
return (
<React.Fragment>
{ userLinks.exists ? <h1>Loaded and works!</h1> : <h1>Didn't work</h1> }
</React.Fragment>
firebaseconfig.js
class Firebase {
constructor() {
firebase.initializeApp(firebaseConfig);
this.auth = firebase.auth();
this.db = firebase.firestore();
}
async getUserInfo (username) {
let userInfo = { exists: false }
await this.db.collection("users").doc(username).get().then(doc => {
if (doc.exists) {
console.log("Document data:", doc.data());
userInfo.exists = true;
userInfo = { ...userInfo, links: doc.data().links };
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
return userInfo;
}
export default new Firebase();
【问题讨论】:
-
错误提示你正在尝试渲染一个 Promise。
userLinks的输出是什么? -
@AdamAzad Ah 发现 userLinks 的输出是一个
,但是如何获取这个 promise 的 .then() 值并及时更新到 react 组件呢?我应该像上面那样使用 useState 吗? (我更新了帖子)
标签: javascript firebase asynchronous google-cloud-firestore