【发布时间】:2021-04-22 02:22:00
【问题描述】:
以下是一个组件,它映射上下文变量中的对象并呈现它们。
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);
}
恳请您抽出宝贵的时间,为我的问题提供一些解决方案。
非常感谢。
【问题讨论】:
标签: reactjs firebase redux react-context