我有一个问题,我开始怀疑它没有解决方案,除非我删除React并返回jQuery。我想创建一个类似于https://tenno.tools/或https://deathsnacks.com/wf/的应用。这些是抓取JSON数据并定期更新的网站。
我想创建一个使用axios的反应应用程序,每分钟使用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?
但是,我又开始怀疑这实际上是不可能的。是吗?
答案 0 :(得分:0)
您希望在setInterval
上使用axiosFunc
,无需在网络请求中进行设置。这是一个每5秒调用一次API并呈现格式化日期的示例。
class Example extends React.Component {
constructor() {
super();
this.state = { alerts: [] };
}
axiosFunc = () => {
axios.get('https://api.warframestat.us/pc').then(results => {
this.setState({
alerts: results.data.alerts,
});
console.log('Updated the data!', results);
});
};
timer = time => {
// Your timer code goes here, just printing out example data here.
const date = new Date(time);
return `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
};
componentDidMount() {
this.axiosFunc();
this.interval = setInterval(this.axiosFunc, 5000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
if (!this.state.alerts.length) {
return <div />;
}
// Sorting the alerts every time we render.
const latest = this.state.alerts.sort((a, b) => {
return new Date(b.activation) - new Date(a.activation);
})[0];
return <div>{this.timer(latest.activation)}</div>;
}
}
ReactDOM.render(<Example />, document.getElementById('root'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.min.js"></script>
<div id="root"></div>
&#13;
答案 1 :(得分:0)
这绝对有可能。正如你所说,所有这些都有效 - 哪一部分实际上给你带来了麻烦?你在哪里得到错误吗?
就我个人而言,我想在这样的应用程序中使用Redux和React,因为我喜欢将数据的提取与数据的呈现分开,但这只是个人偏好。我有an example app that uses setInterval directly in a React component,以防从setTimeout
移至setInterval
导致您痛苦。