【发布时间】:2021-02-06 06:23:21
【问题描述】:
我有一个 firebase 数据库,它有一个名为“post”的集合,在 post 中有 6 个变量(displayName、userName、verified、text、image、avatar)。这个想法是,数据库中会有多个帖子。
反应代码:
const [posts, setPosts] = useState([]);
//Whenever the firebase database changes, it runs this method
useEffect(() => {
db.collection("posts").onSnapshot((snapshot) =>
//Loops through all the posts and adds the data into an array
setPosts(snapshot.docs.map((doc) => doc.data()))
);
}, []);
在 react 中,我有两个状态变量,posts 和 setPosts。我假设它们最初只是设置为空数组。
现在我有了useEffect 函数,我被告知只要数据库更改/更新就会运行该函数。第一个问题,函数如何知道数据库更新了?换句话说,useEffect 函数是如何工作的?
其次,我很确定,post 变量最终会成为数据库中所有 post 对象的列表。我不确定那是怎么发生的。我在上面附上了更新此状态的代码,但我不太确定它是如何工作的。你能把它分解并解释它是如何工作的吗?我也不确定 setPosts 状态的用途。
请告诉我!
【问题讨论】: