我在我的本机应用程序中使用了很多 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
钩子设置空依赖数组的方式,当快照回调被更新的数据触发并且我尝试用新的更改修改当前状态时,当前状态是未定义的。我相信这是因为关闭。我能得到它的周围使用useRef
了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
与 a 一起使用forceUpdate
而不useState
是以不同的方式来正确地做到这一点吗?我不得不更新一个useRef
钩子并forceUpdate()
在我的应用程序中调用似乎是不对的。尝试时,useState
我尝试将状态变量添加到依赖项数组,但结果是无限循环。我只希望快照函数被初始化一次,并且组件中的有状态数据随着后端的变化(在 onSnapshot 回调中触发)而随着时间的推移而更新。