问题:哪个反应钩子与firestore onsnapshot一起使用?

我在我的 react native 应用程序中使用了很多 firestore 快照。我也在使用 React 钩子。代码看起来像这样:

useEffect(() => {
    someFirestoreAPICall().onSnapshot(snapshot => {

        // When the component initially loads, add all the loaded data to state.
        // When data changes on firestore, we receive that update here in this
        // callback and then update the UI based on current state

    });;
}, []);

起初我认为useState将是存储和更新 UI 的最佳钩子。但是,根据我的useEffect钩子设置为空依赖数组的方式,当快照回调被更新的数据触发并且我尝试使用新的更改来修改当前状态时,当前状态是未定义的。我相信这是因为关闭。我可以使用useRefforceUpdate()来解决它,如下所示:

const dataRef = useRef(initialData);

const [, updateState] = React.useState();
const forceUpdate = useCallback(() => updateState({}), []);

useEffect(() => {
    someFirestoreAPICall().onSnapshot(snapshot => {

       // if snapshot data is added
       dataRef.current.push(newData)
       forceUpdate()

       // if snapshot data is updated
       dataRef.current.find(e => some condition) = updatedData
       forceUpdate()

    });;
}, []);

return(
// JSX that uses dataRef.current directly
)

我的问题是我是否通过使用useRefforceUpdate而不是useState以不同的方式正确地做到这一点?我必须更新useRef钩子并在我的应用程序中调用forceUpdate()似乎不正确。在尝试useState时,我尝试将状态变量添加到依赖数组中,但最终出现了无限循环。我只希望快照函数被初始化一次,并且组件中的有状态数据随着后端的变化(在 onSnapshot 回调中触发)随着时间的推移而更新。

解答

一个简单的 useEffect 对我有用,我不需要创建辅助函数或任何东西,

useEffect(() => {
        const colRef = collection(db, "data")
        //real time update
        onSnapshot(colRef, (snapshot) => {
            snapshot.docs.forEach((doc) => {
                setTestData((prev) => [...prev, doc.data()])
                // console.log("onsnapshot", doc.data());
            })
        })
    }, [])
Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐