gpt4 book ai didi

javascript - 使用 es6 与 native react 创建计时器

转载 作者:技术小花猫 更新时间:2023-10-29 11:03:27 26 4
gpt4 key购买 nike

我想在我的应用程序中添加一个计时器,该应用程序是使用 React Native 构建的。

我查看了 timer mixin 的链接在文档中,但是我已经使用 es6 构建了应用程序的其余部分,因此这将不兼容。

我试过下面的。

在我的主类中,我有一个函数叫做 getTimerCountDown

getTimerCountDown() {
setTimeout(() => {
this.setTimeRemaining(this.getTimeRem()-1);
}, 1000);
}

getTimeRem() {
return this.state.timeRemaining;
}

我试过在 componentDidUpdate 中调用它,如下所示。如果我不与 UI 进行任何其他交互,这会按照我的意愿工作。

如果我这样做(例如,我有一个按钮,我可以点击 View 。)当 `componentDidUpdate 再次被调用时,计数器变得非常快(因为它被调用 x 次)

componentDidUpdate(){
this.getTimerCountDown();
}

我不确定我是否完全走错了路,或者对我所做的事情稍作改变就能得到我想要的东西。使用 es6 让倒数计时器在 React Native 中工作的最佳方法是什么?

定时器类在主页上

<Timer timeRem={this.getTimeRem()} />

返回

render(){
return (
<View style={styles.container}>
<Text> This is the Timer : {this.props.setTimer} - {this.props.timeRem} </Text>
</View>
)
}

最佳答案

即使没有任何其他 UI 交互,我也不确定这将如何工作。每次重新渲染组件时都会调用 componentDidUpdate,这是在内部状态或传递的 props 发生变化时发生的事情。不是你可以指望每一秒都会发生的事情。

如何将 getTimerCountDown 移动到您的 componentDidMount 方法(仅调用一次),然后使用 setInterval 而不是 setTimeout 以确保计数器连续递减?

关于javascript - 使用 es6 与 native react 创建计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31963803/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com