[英]How to get the value of useRef current in React Native
I am developing a React Native application and am facing the following error:我正在开发 React Native 应用程序并面临以下错误:
I have defined a useRef
which stores the doc ID from a firebase collection.我定义了一个
useRef
,它存储来自 firebase 集合的文档 ID。 But when I call that variable after it has been defined, the .current
value returns a blank string.但是当我在定义该变量后调用它时,
.current
值返回一个空字符串。
db.collection('users').onSnapshot((snapshot) => {
snapshot.docs.map((doc) => {
if (doc.data().email === auth.currentUser?.email) {
bidId.current = doc.id
console.log(bidId.current)
}
})
})
The above code returns the expected value.上面的代码返回预期值。 However, when I call the variable outside this
db.collection
loop, I get the following value:但是,当我在此
db.collection
循环之外调用变量时,我得到以下值:
But calling the bidId.current returns a blank string.但是调用 bidId.current 会返回一个空字符串。
Please can someone help me with this.请有人帮我解决这个问题。 Thanks!
谢谢!
Actually this is what happens:实际上是这样发生的:
db.collection('users').onSnapshot((snapshot) => {
snapshot.docs.map((doc) => {
if (doc.data().email === auth.currentUser?.email) {
bidId.current = doc.id
// This line gets executed after some time!
console.log(bidId.current)
}
})
})
// This gets executed first! (The value has not been stored yet!)
console.log(bidId.current);
Using the "useState" hook instead of "useRef" will solve the issue.使用“useState”挂钩而不是“useRef”将解决问题。 Consider the following code:
考虑以下代码:
const [BidId, setBidId] = useState<string | null>(null);
// This will store the value...
useEffect(() => {
db.collection('users').onSnapshot((snapshot) => {
snapshot.docs.map((doc) => {
if (doc.data().email === auth.currentUser?.email) {
setBidId(doc.id);
}
})
})
}, []);
// Here you can access the value
useEffect(() => {
if(BidId !== null)
console.log(BidId);
}, [BidId]);
// You can also return the component like the following:
return (<View>The Bid ID is: {BidId !== null ? BidId : "Loading..."}</View>);
Your useEffect basically says that whenever pageRef changes, call this function. If done outside, it will call do your tasks on every render instead of doing the whenever pageRef values is changed.您的 useEffect 基本上表示每当 pageRef 更改时,调用此 function。如果在外部完成,它将在每次渲染时调用执行您的任务,而不是在 pageRef 值更改时执行。 Also, in initial renders, it may give undefined values.
此外,在初始渲染中,它可能会给出未定义的值。 You can only return a function in useEffect which basically says that before running the same next time, run this function before.
您只能在 useEffect 中返回 function,这基本上表示在下次运行相同之前,先运行此 function。
Try (currentUser without the '?' query character):尝试(不带“?”查询字符的 currentUser):
if (doc.data().email === auth.currentUser.email) {
bidId.current = doc.id
console.log(bidId.current)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.