简体   繁体   English

如何在按钮单击时更新 state 以响应原生 expo

[英]How to update state in react native expo on button click

I used react-native-countdown-timer component.我使用了 react-native-countdown-timer 组件。 I have used useEffect previously to start timer which is running perfectly but when I change to on press function react state is not updating我以前使用 useEffect 来启动运行完美的计时器,但是当我更改为按下 function 时,反应 state 没有更新

This is the Code of Component这是组件的代码

const [totalDuration, setTotalDuration] = useState(0);

const OnCountDown = () => {
    var date = moment().format("YYYY-MM-DD hh:mm:ss");
    var expirydate = moment().add(4, "hours").format("YYYY-MM-DD hh:mm:ss"); //You can set your own date-time
    console.log(date);
    console.log(expirydate);
    var diffr = moment.duration(moment(expirydate).diff(moment(date)));
    var hours = parseInt(diffr.asHours());
    var minutes = parseInt(diffr.minutes());
    var seconds = parseInt(diffr.seconds());
    var d = hours * 60 * 60 + minutes * 60 + seconds;
    setTotalDuration(d);
  };



<IconButton
              icon={"qrcode-scan"}
              size={40}
              onPress={() => {
                setOnline(true);
                OnCountDown();
              }}
            />

<CountDown
          until={totalDuration}
          timeToShow={["H", "M", "S"]}
          onFinish={() => alert("finished")}
          // onPress={() => alert("hello")}
          size={20}
        />

I think your requirement is to start counter on a button press and you couldn't achieve that because there isn't any option for start the counter for react-native-countdown-timer component since its working is to provide duration on initial phase and it will auto start.我认为您的要求是在按下按钮时启动计数器,但您无法实现这一点,因为没有任何选项可以启动react-native-countdown-timer component的计数器,因为它的工作是在初始阶段提供持续时间和它会自动启动。 So to achieve what you want there were some alternative libraries所以为了实现你想要的,有一些替代库

  1. react-native-flip-countdown-timer : which have play props and react-native-flip-countdown-timer :具有play 道具

  2. react-native-stopwatch-timer : which have start props react-native-stopwatch-timer :具有start 道具

which are boolean, you can set this to true on button press.它们是 boolean,您可以在按下按钮时将其设置为 true。

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

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