我正在开发一个React Native应用程序,在这里我要从API提取数据。现在每天从下午6点到晚上7点,我需要以3秒的间隔时间重新加载API数据,因为在此期间数据一直在变化。我不知道该怎么做。这是我现在拥有的代码:
async componentDidMount() {
await fetch('https://api', {
method: 'GET',
})
.then((response) => response.json())
.then((response) => {
this.setState({ tableData1: response.magnum })
this.setState({ tableData2: response.special })
this.setState({ tableData3: response.consolation })
this.setState({ date: response.date })
this.setState({ draw: response.draw })
})
}
componentWillMount() {
const { navigation } = this.props;
this.focusListener = navigation.addListener("didFocus", () => {
var today = new Date()
var time = today.getHours()
console.log(today.getMinutes())
var weekDay = today.getDay()
if ((time >= 18) && (time <= 19 )) {
// I guess I need to do something here...
}
});
如果在componentWillMount中执行某些操作,每3秒一次又一次刷新数据,我会感到困惑。任何帮助将不胜感激。
答案 0 :(得分:1)
我可能会做这样的事情:
main.h
让我们说您在6:21开始进行API调用,因此您希望继续进行API调用剩下的39分钟,即componentWillMount() {
const { navigation } = this.props;
this.focusListener = navigation.addListener("didFocus", () => {
var today = new Date()
var time = today.getHours()
console.log(today.getMinutes())
var weekDay = today.getDay()
if ((time >= 18) && (time < 19 )) {
var setIntervalId = setInterval(() {
// make api call;
}, 300);
var min = 60 - today.getMinutes();
var mili = min * 60000;
setTimeout(() => clearInterval(setIntervalId), mili);
}
});
变量,因为setTimeout函数接受以毫秒为单位的持续时间值,所以我刚刚将其转换为毫秒。