gpt4 book ai didi

react-native - 每 x 秒更新一次状态

转载 作者:行者123 更新时间:2023-12-04 00:03:56 26 4
gpt4 key购买 nike

我试图每 3 秒更新一次状态。

export default class Calendar extends Component {
constructor(props) {
super(props);

this.state = {
timeLineTop: 75,
};
}

render() {
this.state.timeLineTop = setInterval(function () {
let d = new Date();
let result = d.getHours() + d.getMinutes() / MINUTES_IN_HOUR;

return result;
}, 3000);

<View style={[
{ top: this.state.timeLineTop },
]}></View>
}
}

为什么这不会每 3 秒更新一次我的 View 位置?

最佳答案

** 更新以实现 TimerMixin

您需要调用 this.setState 来更新状态变量,并按照指定
@eyal83,将 TimerMixin 用于 setTimeout 和 setInterval:

var TimerMixin = require('react-timer-mixin');

componentDidMount: function() {
this.setInterval( () => {
let d = new Date();
let result = d.getHours() + d.getMinutes() / MINUTES_IN_HOUR;
this.setState({
timeLineTop: result
})
}, 500);
}

我还设置了一个基本应用程序,使用 setInterval here 重置状态变量,代码如下。 https://rnplay.org/apps/9gD-Nw
'use strict';

var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
} = React;

var TimerMixin = require('react-timer-mixin');

var SampleApp = React.createClass({
mixins: [TimerMixin],
getInitialState: function() {
return {
timeLineTop: 75
}
},

componentDidMount: function() {
this.setInterval( () => {
this.setState({
timeLineTop: this.state.timeLineTop+1
})
}, 500);
},

render: function() {

return (
<View style={styles.container}>
<View style={[
{ marginTop: this.state.timeLineTop },
]}><Text>TOP - {this.state.timeLineTop}</Text></View>
</View>
);
}
});

var styles = StyleSheet.create({
container: {
flex: 1,
marginTop:60,
},
});

AppRegistry.registerComponent('SampleApp', () => SampleApp);

关于react-native - 每 x 秒更新一次状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34243685/

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