【发布时间】:2018-06-30 11:30:52
【问题描述】:
我开始怀疑我有一个问题没有解决方案,除非我放弃 React 并返回到 jQuery。我想创建一个类似于https://tenno.tools/ 或https://deathsnacks.com/wf/ 的应用程序,这些站点会获取 JSON 数据并定期更新。
我想制作一个使用 axios 的 react 应用,通过 setTimeout 每分钟刷新一次数据,因为数据经常变化。
axiosFunc = () => {
axios.get('https://api.warframestat.us/pc').then(results => {
this.setState({
alerts: results.data.alerts
});
setTimeout(this.axiosFunc,1000 * 60);
})
}
componentDidMount() {
this.axiosFunc();
}
接下来我需要使用 map 循环遍历警报数组的对象,并根据对象的活动数据制作各个组件。
render() {
return (
<main className="content">
<header>{this.state.whichEvent.toUpperCase()}</header>
{this.state.alerts.map(alert => {
//Variables that pull time based data from the objects go here, and go into the component as props
<AlertsBox key={alert.id}/>
})}
</main>
);
}
然后我使用组件中的 props 和 state 来制作一个计时器,因为来自 JSON 文件的数据有过期日期...
let timer = () => {
//Extract the data from the original string
//Convert the UTC to locale time
let seconds = Math.round((this.state.eta/1000) % 60);
let minutes = Math.floor( (this.state.eta/1000/60) % 60 );
let hours = Math.floor( (this.state.eta/(1000*60*60)) % 24 );
let days = Math.floor( this.state.eta/(1000*60*60*24) );
return `${days >= 1? days + " days" : ""} ${hours >= 1? hours + " hrs" : ""} ${minutes} min ${seconds} sec`
}
所有这些都有效。我能够看到来自 JSON 的动态数据,因为它们进出,以及相应的时间。现在我只需要使用 setInterval 来让计时器每秒滴答一次。这可能吗?我在这里问了类似的问题
How can I return values once per second using react and axios?
但是,我又开始怀疑这实际上是不可能的。是吗?
【问题讨论】:
标签: javascript reactjs axios