我正在开发一个 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 秒一次又一次地刷新数据。任何帮助将不胜感激。
我可能会做这样的事情:
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);
}
});
假设您在 6:21 开始进行 API 调用,因此您希望在剩余的 39 分钟内继续进行 API 调用,这是min
变量,并且由于 setTimeout 函数接受以毫秒为单位的持续时间值,所以我只是将其转换为毫秒。