反应如何保存到变量中,而不是保存到console.log中

问题描述

我对React非常陌生。我可以使用console.log()使用以下函数看到正确的结果,但是如何将结果(是一个数字,而不是一个数组)保存到一个简单变量中。

firestore.collection('games').where('user_ide','==',uid).get().then( (snapshot) => 
    console.log(snapshot.docs.length),);

非常感谢。

解决方法

您在利用状态吗?如果是这样,那么您可以做的是像上面这样初始化状态:

  const [
        snapShot,setSnapShot,] = useState()

并使用

firestore.collection('games').where('user_ide','==',uid).get().then( (snapshot) => 
    setSnapShot(snapshot.docs.length),);

如果它在某个地方不能使用状态,请使用

let snapShot 
firestore.collection('games').where('user_ide',uid).get().then( (snapshot) => 
        snapShot= snapshot.docs.length
        );
,

您可能希望将结果放入状态。例如带钩子

  const [state,setState] = useState("");


firestore.collection('games').where('user_ide',uid).get().then( (snapshot) => 
console.log(snapshot.docs.length),setState(snapshot.docs.length)
);

现在结果将在状态变量中。