react-native - react-native 中的倒数计时器

标签 react-native

当以 react-native 加载屏幕时,我想从 3 倒计时到 1。我用这样的 setTimeOut 尝试过,但没有用。我在这里做错了什么?我怎样才能做到这一点?加载屏幕后,我想以 1 秒的间隔显示 3 =-> 2 ==> 1。这是我的代码。

 constructor(props) {
        super(props);

        this.state = {
            timer: 3
        }
    }

    // componentDidMount 
    componentDidMount() {
        setTimeout(() => {
            this.setState({
                timer: --this.state.timer
            })
        }, 1000);
    }

最佳答案

更新 Hook (使用 useEffect )版本到 倒计时使用 设置间隔 在 native react 中:

const [timerCount, setTimer] = useState(60)

useEffect(() => {
  let interval = setInterval(() => {
    setTimer(lastTimerCount => {
        lastTimerCount <= 1 && clearInterval(interval)
        return lastTimerCount - 1
    })
  }, 1000) //each count lasts for a second
  //cleanup the interval on complete
  return () => clearInterval(interval)
}, []);
使用状态变量 timerCount 作为:<Text>{timerCount}</Text>

关于react-native - react-native 中的倒数计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51695887/

相关文章:

react-native - 在 React-Native 中使用 AsyncStorage 更新状态的正确方法是什么?

reactjs - React-nativeanimate.event 自定义 onScroll 监听器

android - React native 按钮按下不适用于 android

javascript - 分支 IO 深层链接参数未出现在 native react 中

react-native - react native 抽屉导航 : Drawer not closing when pressing an overlay

javascript - Firebase onSnapshot 限制下载

react-native - React Native 是否支持 Apple 的 M1 macbook pro?

ios - 无法在 iOS 上使用 ionic2 退出应用程序?有没有办法退出应用程序?

ios - 在 CI 构建中使用 Facebook iOS SDK - 未找到框架

javascript - 如何将具有通用 Prop 的 React 类组件转换为 Typescript 中的函数组件?