如何让数据在刷新时持久化? [英] How to make data persist on refresh React JS?
本文介绍了如何让数据在刷新时持久化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个代码,其中我装载了一个包含一些Firebase数据的表,但由于某种原因,这些值消失了,我在接下来的两周里一直在努力解决这个问题,我还没有找到这个问题的解决方案,我已经问了两次,到目前为止,我已经尝试了所有方法,但它一直在消失。
重要更新 我只想澄清以下几点,显然我错了,这个问题并不是因为它是一个嵌套集合,正如有人在另一个问题中提到的那样。该问题是因为我在刷新过程中丢失了我的用户。
我将用户从登录带到应用程序,如下所示:
<Estudiantes user={user} />
然后我把它当作道具接受
function ListadoPedidos({user})
但正在迷路,因为当我尝试使用我的火库时迷路:
estudiantesRef = db.collection("usuarios").doc(user.uid).collection("estudiantes")
推荐答案
- 您的代码中的数据流有些矛盾,所以我修改了您的代码,它运行良好。
- 您也可以尝试删除或添加按钮,它将修改Firebase集合,然后更新本地数据。
- 您可以在
codesandbox previewer
(非浏览器)中点击刷新按钮查看数据更新状态。
代码说明如下:
// Set value of `localStorage` to component state if it exist.
useEffect(() => {
const localStorageEstData = window.localStorage.getItem("estudiantes");
localStorageEstData && setEstudiantes(JSON.parse(localStorageEstData));
}, []);
// Sync remote data from firebase to local component data state.
useEffect(() => {
// Subscribe onSnapshot
const unSubscribe = onSnapshot(
collection(db, "usuarios", user.id, "estudiantes"),
(snapshot) => {
const remoteDataSource = snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data()
}));
console.info(remoteDataSource);
setEstudiantes(remoteDataSource);
}
);
return () => {
//unSubscribe when component unmount.
unSubscribe();
};
}, [user.id]);
// when `estudiantes` state update, `localStorage` will update too.
useEffect(() => {
window.localStorage.setItem("estudiantes", JSON.stringify(estudiantes));
}, [estudiantes]);
以下是完整的代码示例:
希望帮助您:)
这篇关于如何让数据在刷新时持久化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文