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

Kev*_*ing 8 firebase reactjs google-cloud-firestore react-native-firebase react-hooks

我在我的本机应用程序中使用了很多 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

    });;
}, []);
Run Code Online (Sandbox Code Playgroud)

起初我认为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
)
Run Code Online (Sandbox Code Playgroud)

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

Jos*_*man 13

如果将 useEffect 和 useState 结合起来会更好。UseEffect 将设置和分离侦听器,useState 可以只负责您需要的数据。

const [data, setData] = useState([]);

useEffect(() => { 
       const unsubscribe = someFirestoreAPICall().onSnapshot(snap => {
         const data = snap.docs.map(doc => doc.data())
         this.setData(data)
       });

       //remember to unsubscribe from your realtime listener on unmount or you will create a memory leak
       return () => unsubscribe()
}, []);
Run Code Online (Sandbox Code Playgroud)

然后,您可以从应用程序中的 useState 挂钩中引用“数据”。

  • 因为这是一个功能组件,所以我不使用“this”关键字。另外,问题是“setData”在快照侦听器中没有按照应有的方式工作。当我在侦听器内使用“setData”时,数据会在组件的下一次渲染时丢失。因此,在初始加载之后,下次后端发生变化并且侦听器触发时,我想查看并修改当前的“数据”,但即使我将其设置为初始加载,它也是未定义的。我访问数据的唯一方法是使用“useRef”,它在渲染之间保存“数据”。 (3认同)
  • 我认为问题在于“onSnapshot”侦听器本身和反应挂钩。如果我在 useEffect 中使用 `, []` 设置状态,但不在 `onSnapshot` 中设置状态,那么事情似乎工作正常。 (2认同)

ans*_*hul 3

一个简单的 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());
            })
        })
    }, [])
Run Code Online (Sandbox Code Playgroud)