我在我的 React Native 应用程序中使用了大量的 Firestore 快照。我也在使用 React hooks。代码看起来像这样:
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
钩子是用一个空的依赖数组设置的,当快照回调被更新的数据触发并且我尝试用新的更改修改当前状态时,当前状态是未定义的。我相信这是因为关闭。我可以使用它来解决它useRef
with a forceUpdate()
像这样:
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
)
我的问题是我通过使用这样做是否正确useRef
连同一个forceUpdate
代替useState
以不同的方式?我必须更新一个,这似乎不对useRef
挂机并通话forceUpdate()
遍布我的应用程序。当尝试时useState
我尝试将状态变量添加到依赖项数组中,但最终出现无限循环。我只希望快照函数初始化一次,并且随着后端情况发生变化(在 onSnapshot 回调中触发),组件中的状态数据会随着时间的推移而更新。
如果将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()
}, []);
然后,您可以从应用程序中的 useState 挂钩引用“数据”。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)