javascript 如何调用函数一次?

bq3bfh9z  于 2022-12-21  发布在  Java
关注(0)|答案(2)|浏览(188)

我在react native中有一个项目,我需要实时从firebase数据库读取数据。我尝试:

const [numberTrains, setNumberTrains] = useState(0)
 function Read(){
    const starCountRef = ref(db, 'users/' + user.localId);
    onValue(starCountRef, (snapshot) => {
      const data = snapshot.val();
      setNumberTrains(data.countTrains);   
    });
  }
  Read()
    console.log(numberTrains)

但它抛出异常:Error: Too many re-renders. React限制渲染的次数以防止无限循环。输出如下所示:

LOG  0
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1
 LOG  1

如何才能只读取numberTrain中的数据一次?

y0u0uwnf

y0u0uwnf1#

使用使用效果

const [numberTrains, setNumberTrains] = useState(0)

function Read(){
  const starCountRef = ref(db, 'users/' + user.localId);
  onValue(starCountRef, (snapshot) => {
    const data = snapshot.val();
    setNumberTrains(data.countTrains);   
  });
}

React.useEffect(()=>{
  Read();
  console.log(numberTrains)
},[]);
daolsyd0

daolsyd02#

useEffect(()=>{
  Read()
},[])

如果数据仅为一次,则它将仅调用一次建议,在调用读取之前检查numberTrains长度

相关问题