React Native放了一个"Cooldown"在按钮上 [英] React Native put a "Cooldown" on a Button

查看:50
本文介绍了React Native放了一个"Cooldown"在按钮上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是,是否可以对用户按下的按钮进行冷却,或者仅在2秒钟之内进行一次注册.我正在使用与REST API和PostgreSQL DB连接的React Native(Expo).

my question is if it is possible to put a cooldown on a button that the user presses, or to only register like 1 press in 2 seconds. I am using React Native (Expo) connected with a REST API and a PostgreSQL DB.

我的问题是我有一个将数据发送到数据库的按钮.OnPress输入的值已被存入数据库,并且用户被导航到另一个屏幕,在该屏幕上他可以看到他的输入.

My problem is that I have a Button that sends data to a Database. OnPress the entered Values are PUT to the database and the User gets navigated to another Screen where he can see his entry.

我注意到,当用户足够快时,他可以按下按钮两次或3次,因此数据也将2/3次发布到数据库.

I noticed that when a user is fast enought he can press the button twice or 3 times and therefore the data also is posted 2/3 times to the db.

我需要大约一秒钟的冷却时间,因此数据仅发布1次,因为导航几乎立即发生!

I would need something like one second cooldown so the data is only posted 1 time because the navigation almost happens immediatly!

我在互联网上找不到任何东西.

I could not find anything in the internet on this.

感谢〜Faded

推荐答案

在按下按钮后立即将其禁用.

Make the button disabled as soon as it's pressed.

const MyComponent = ({makePutCall}) => {
   const [disabled,setDisabled] = useState(false);

   const doPut = async () => {
       setDisabled(true);
       await makePutCall();
       setDisabled(false);
   }

   return <Button disabled={disabled} onPress={doPut}/>
 
}

或使用ref防止多次推送:

or use a ref to prevent pushing more than once:

const MyComponent = ({makePutCall}) => {
   const disabled = useRef(false);

   const doPut = async () => {
       if(disabled.current) return;
       disabled.current = true;
       await makePutCall();
       disabled.current = false;
   }

   return <Button onPress={doPut}/>
 
}

我最喜欢的人是微调器,就像你说的那样:

My person favourite is a spinner, like you said:

const MyComponent = ({makePutCall}) => {
   const [showSpinner,setShowSpinner] = useState(false);

   const handlePress = async () => {
      setShowSpinner(true);
      await makePutCall();
      setShowSpinner(false);
   }

   return showSpinner ? <Spinner/> : <Button onPress={handlePress}/>
}

或者以另一种方式做-不要使用计时器.

or do it another way - DON'T USE A TIMER.

这篇关于React Native放了一个"Cooldown"在按钮上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆