【问题标题】:Updating state in react async not behaving right在反应异步中更新状态行为不正确
【发布时间】: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


【解决方案1】:

所以问题是必须在另一个 useEffect 中完成初始提取,否则文档会相互覆盖,因此只有最后提取的文档会保持在该状态。所以我把代码改成了这个

//State to mark that all students have been fetched from firestore on mount
const [initialFetchDone, setInitialFetchDone] = useState(false);

 useEffect(() => {
        const db = firestore();
        db.collection(CLASS_COLLECTION).doc(id).get().then(snapshot => {
            const fetchedClass = snapshot.data() as Class;
            setClass(fetchedClass);
            const docs = fetchedClass.students.map(doc => doc.get());
            Promise.all(docs).then(docs => docs.map(doc => doc.data())).then(_students => setStudents(_students as Student[])
            ).then(() => setInitialFetchDone(true))
        })
    }, [id]);

    useEffect(() => {
            const db = firestore();
            const unsubscribeCallbacks: (() => void)[] = [];
            //The initial fetched is handled in the other effect
            if (initialFetchDone) {
                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({includeMetadataChanges:true},studentSubscribe);
                        unsubscribeCallbacks.push(unsubscribe)
                    }
                })
                return () => {
                    for (let unsubscribe of unsubscribeCallbacks) {
                        unsubscribe();
                    }
                }
            }
        }, [id, _class, initialFetchDone]
    );


    function studentSubscribe(snapshot: DocumentSnapshot) {
        const _students = [...students];
        //Ignore local changes
        if (!snapshot.metadata.hasPendingWrites) {
            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) {
                _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 {

                _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;
                });
            }
        }
        setStudents(_students);
    }

对于我的用例,我必须忽略本地更改,因此与本地更改相关的修改和侦听元数据更改与我最初的问题无关。

【讨论】:

    猜你喜欢
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 2021-07-22
    • 1970-01-01
    • 2021-01-31
    • 2022-01-05
    • 2021-04-29
    相关资源
    最近更新 更多