【发布时间】:2020-04-21 00:59:41
【问题描述】:
我正在尝试在 useEffect() 挂钩中设置对一系列 firebase 文档的订阅,如下所示:
useEffect(() => {
const db = firestore();
const unsubscribeCallbacks: (() => void)[] = [];
db.collection(CLASS_COLLECTION).doc(id).get().then(doc => {
const classData = doc.data() as Class;
for (let student of classData.students) {
const unsubscribe = student.onSnapshot(studentSubscribe);
unsubscribeCallbacks.push(unsubscribe)
}
})
return () => {
for (let unsubscribe of unsubscribeCallbacks) {
unsubscribe();
}
}
}, [id]
);
studentSubscribe 是我处理从数据库中获取的数据并更新状态的函数:
function studentSubscribe(snapshot: DocumentSnapshot) {
const _students = students;
const studentData = snapshot.data() as Student;
//Check if this snapshot is a student update or a new student
//Also true on the first fetch
const isStudent = _students.find(val => val.id === studentData.id)
if (isStudent) {
console.log("Student updated")
console.log(studentData)
_students.map(val => val.id === studentData.id ? studentData : val)
//Sort alphabetically
_students.sort((a, b) => {
if (a.name < b.name)
return -1;
else if (a.name === b.name)
return 0;
return 1;
});
} else {
console.log("New student pushed to state")
console.log(studentData)
_students.push(studentData);
//Sort alphabetically
_students.sort((a, b) => {
if (a.name < b.name)
return -1;
else if (a.name === b.name)
return 0;
return 1;
});
}
console.log("Pushing to state");
console.log(_students);
updateStudents(_students);
}
另外,updateStudents 只是一个辅助函数,因此我可以添加一些额外的日志记录:
function updateStudents(newState:Student[]){
console.log('Old state')
console.log(students)
console.log('New state');
console.log(newState);
setStudents(newState);
}
学生状态用一个空数组初始化。问题是从数据库中获取数据并更新状态后,状态更改不会反映在重新渲染中。我在接收student 状态作为道具的组件中设置了日志。当它是一个空数组时它会被记录,但在它被更新后不会被记录,这意味着状态更新不会在 props 更新中传播。
我还在那个辅助函数中看到了一些奇怪的行为。 “旧状态”日志从不记录第一次调用时应该记录的空数组。我从不设置没有该函数的状态,因此当状态从空数组的初始值更改为其他值时应该调用。相反,我得到的第一个旧状态日志是从数据库中获取的数据。不过,所有其他日志看起来都还不错。
知道这里出了什么问题吗?提前致谢!
更新:
在studentSubscribe 中,将const _students = students 更改为const _students = [...students] 部分解决了问题,因为现在状态变量没有搞砸。
现在,在 students 数组中,从 firestore 获取所有文档后,似乎只保留了上次获取的文档中的数据。
【问题讨论】:
-
useEffect 必须依赖于 studentState,例如 [id, students, setStudents]
-
这个 useEffect 修改了
students状态,所以将students作为依赖项传入不会导致无限循环? -
只有在“id”改变时才需要获取数据
-
每当id发生变化,这是一个状态属性,我需要更改我订阅的文档
-
是的,找到了问题。当复制局部变量
_students中的students时,我直接分配数组而不是使用[...students]复制它。现在我有了另一个,students数组包含刚刚从 firestore 检索到的最后一个文档中的数据。让我更新帖子
标签: javascript reactjs google-cloud-firestore react-hooks