我有一个数据库侦听器,该侦听器必须访问组件属性(可以在组件的整个生命周期内更改)。我的问题是,当我在侦听器的本地范围内时,全局范围内的内容不会更新。例如,假设我有一个道具“ userData”,它首先具有以下形式:
{
name: "anthony"
}
在未指定的时间后,Add将其字段值更改为“ mark”。
如果我运行此代码:
console.log("Global: " + props.userData) <----------------- Before: {name: "anthony"} ; After: {name: "mark"} OK
const onPostsCollectionUpdate = (snapshot) => {
/*
This function gets the initial amount of posts
and the new ones that are uploaded in real time.
*/
console.log("Local: " + props.userData) <----------------- Before: {name: "anthony"} ; After: {name: "anthony"} NOT UPDATED!
...
}
useEffect(() => {
const { firebase, attachListener } = props;
// Create a Real-time Database listener
const postsListener = firebase
.getDatabase()
.collection("posts")
.doc(firebase.getCurrentUser().uid)
.collection("userPosts")
.orderBy("date")
.limitToLast(MAX_POSTS_TO_RETRIEVE_LENGTH)
.onSnapshot(onPostsCollectionUpdate); // Get the initial amount of posts
// Attach the listener
attachListener(postsListener);
}, []);
我得到这个结果:
全局:{“ name”:“ anthony”}
当地:{“ name”:“ anthony”}
全局:{“ name”:“ mark”}
当地:{“ name”:“ anthony”}
如您所见,在方法“ onPostsCollectionUpdate”内,道具未更新。我也尝试过使用状态变量和相同的结果。
有什么想法为什么会发生这种情况以及如何在侦听器的本地范围内获取最新值?
谢谢。
尝试使用此代码
import React, { useCallback } from 'react';
console.log("Global: " + props.userData) <----------------- Before: {name: "anthony"} ; After: {name: "mark"} OK
const onPostsCollectionUpdate = (snapshot) => {
/*
This function gets the initial amount of posts
and the new ones that are uploaded in real time.
*/
console.log("Local: " + props.userData) <----------------- Before: {name: "anthony"} ; After: {name: "anthony"} NOT UPDATED!
...
}
const initializeListener = useCallback(() => {
const { firebase, attachListener } = props;
// Create a Real-time Database listener
const postsListener = firebase
.getDatabase()
.collection("posts")
.doc(firebase.getCurrentUser().uid)
.collection("userPosts")
.orderBy("date")
.limitToLast(MAX_POSTS_TO_RETRIEVE_LENGTH)
.onSnapshot(onPostsCollectionUpdate); // Get the initial amount of posts
// Attach the listener
attachListener(postsListener);
}, [props]);
useEffect(() => {
initializeListener();
}, [initializeListener]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句