以下是通过上下文变量中的对象映射并呈现它们的组件。
const MyGroups = () => {
const { myGroups } = useContext(GlobalContext);
return (
<div className="my__groups">
<h1 className="my__groups__heading">My Groups</h1>
<div className="my__groups__underline"></div>
<div className="my__groups__grid__container">
{
myGroups.map(({id, data}) => (
<GroupCard
key={id}
name={data.name}
image={data.image}
/>
))
}
</div>
</div>
)
}
下面是我的 store 函数,我用它从 Firebase 获取我的数据并将动作分派给 Reducer。
function fetchGroupsFromDatabase(id) {
let myGroups = [];
db.collection("users").doc(id).get() // Fetch user details with given id
.then(doc => {
doc.data().groupIDs.map(groupID => { // Fetch all group IDs of the user
db.collection("groups").doc(groupID).get() // Fetch all the groups
.then(doc => {
myGroups.push({id: doc.id, data: doc.data()})
})
})
})
.then(() => {
const action = {
type: FETCH_GROUPS_FROM_DATABASE,
payload: myGroups
};
dispatch(action);
})
}
现在,问题是我想要渲染的“GroupCards”没有渲染,尽管我可以在控制台中看到一段时间后填充了上下文变量。
与 setTimeout() 完美配合
但是,我观察到,如果我在几秒钟后通过 setTimeout 分派我的操作,而不是在 THEN 构造中分派动作,我的组件将完美呈现,如下所示:
function fetchGroupsFromDatabase(id) {
let myGroups = [];
db.collection("users").doc(id).get() // Fetch user details with given id
.then(doc => {
doc.data().groupIDs.map(groupID => { // Fetch all group IDs of the user
db.collection("groups").doc(groupID).get() // Fetch all the groups
.then(doc => {
myGroups.push({id: doc.id, data: doc.data()})
})
})
})
setTimeout(() => {
const action = {
type: FETCH_GROUPS_FROM_DATABASE,
payload: myGroups
};
dispatch(action);
}, 3000);
}
我谦虚地请求您抽出宝贵的时间,并为我的问题提供一些解决方案。
非常感谢你。