【发布时间】:2020-03-06 12:24:31
【问题描述】:
这是我的代码,我希望从 Firestore 获取关注者数据,然后从 doc id 获取用户,但我在控制台日志中获取数据,但数据未在第一次组件渲染时显示,但当我单击时该选项卡第二次呈现数据和正确的追随者用户显示有人可以告诉我我做错了什么吗?
export default function RequestTab() {
const [followers, setfollowers] = useState(null)
useEffect(() => {
if (firebase.auth().currentUser) {
let data = [];
db.collection("buddiez")
.where("followeeId", "==", firebase.auth().currentUser.uid)
.where("accepted", "==", false)
.onSnapshot((querySnapshot) => {
querySnapshot.forEach((doc) => {
db.collection("users").doc(doc.data().followerId).get().then((result) => {
data.push({ ...result.data() })
});
});
});
setfollowers(data)
}
}, [])
console.log(followers);
let userArr = followers ? followers.map((follower, i) => {
return <div key={i} className="request-details pb-3 border-bottom">
<div className="noty-usepf-icon">
<img className="rounded-circle mt-0" style={{ width: "45px", height: "45px" }} src={follower.profilePic ? follower.profilePic : ""} alt="" />
</div>
<div className="request-info">
<h3 className="mb-n1" style={{ fontSize: '1.1rem' }}>{follower.fullName}</h3>
<span>@{follower.username}</span>
</div>
<div className="accept-feat">
<ul>
<li><button type="submit" className="accept-req">Accept</button></li>
<li><button type="submit" className="close-req"><i className="la la-close" /></button></li>
</ul>
</div>
</div>
}) : <h2 className="text-muted p-3 d-flex justify-content-center">No Requests !</h2>
return (
<div className="tab-pane show active">
<div className="acc-setting">
<h3>Requests</h3>
<div className="requests-list">
{userArr}
</div>
</div>
</div>
)
}
【问题讨论】:
-
您没有考虑到这是一个异步调用,并且调用基本上总是比第一次渲染花费更长的时间。适当编码。
-
我尝试了一些东西,但仍然没有得到想要的结果,请你告诉我怎么做...@DaveNewton
-
当数据不存在时处理渲染。
-
非常感谢您的帮助...我只是设置了一个 isFetching 状态并在获取数据然后渲染它时使其变为真...@DaveNewton