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钩子设置空依赖数组的方式,当快照回调被更新的数据触发并且我尝试用新的更改修改当前状态时,当前状态是未定义的。我相信这是因为关闭。我能得到它的周围使用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
)
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 挂钩中引用“数据”。
一个简单的 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)
| 归档时间: |
|
| 查看次数: |
9552 次 |
| 最近记录: |