简体   繁体   English

当我登录/打开应用程序时,如何只调用一次该函数

[英]How to call the function only once, when i make a login/open app

I have got a function and need only once call it, when the suer make login.我有一个函数,只需要在用户登录时调用一次。

 function Read(){
    const [counter, setCounter] = useState(1);
    const starCountRef = ref(db, 'users/' + user.localId);
    
    onValue(starCountRef, (snapshot) => {
        const data = snapshot.val();
        setCounter(data.countTrains);   
    });
  }

  useEffect(() => {
      Read();
      console.log('counter:', counter)
  },[]);

I need to write data here into counter variable我需要将这里的数据写入计数器变量

I am not sure what you want to achieve, here is your function我不确定你想要实现什么,这是你的功能

const functionThatIsCalledOnlyOnce = ( counterValue ) => {
   setCounter(counterValue)
}

When you want to call this function?你想什么时候调用这个函数? if you want to call it only once, when app open put it in useEffect:如果你只想调用它一次,当应用程序打开时把它放在 useEffect 中:

  useEffect(()=>{
   functionThatIsCalledOnlyOnce(1);
  },[]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM