如何在React JS中进行Ajax调用自动刷新 [英] How to make ajax call auto refresh in react js
本文介绍了如何在React JS中进行Ajax调用自动刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使此页面自动刷新,在3分钟之内对后端进行ajax调用,该如何设置?我在想的是在ajax中设置一个间隔,使其每3分钟自动调用一次?有什么办法可以实现呢?还是有更好的解决方案来实现这一点?
I need to make this page auto refresh, make the ajax call to the backend 3 mins like, how to setup this? What I am thinking is set a interval in ajax, make it automatically call every 3 mins? Is there any way to implement this? Or there is any better solution to implement this?
export default class InventoryLevelReport extends React.Component {
constructor() {
super();
this.state = {
data: [
{
sku: null,
inventoryCount: 0
}
],
url: '/mft/api/reports/inventory-view'
};
}
sortByCount() {
this.setState({data: _.orderBy(this.state.data, (i) => i.inventoryCount)});
}
componentDidMount() {
ajax(this.state.url, {
success: data => {
console.log(data);
this.setState({data: data.data});
}
});
}
render() {
const buttonStyle = {
position: 'relative',
float: 'right'
};
return <div className="content">
<Button style={buttonStyle} onClick={() => this.sortByCount()}>Sort</Button>
<div>
<Table tableType='bordered'>
<th>SKU</th>
<th>Count</th>
<tbody>
{this.state.data.map((data, i) => <InventoryTableRow data={data} key={i} />)}
</tbody>
</Table>
</div>
</div>;
}
}
class InventoryTableRow extends React.Component {
render() {
return (
<TableRow>
<TableColumn>{JSON.stringify(this.props.data.sku).split('"').join('')}</TableColumn>
<TableColumn>{JSON.stringify(this.props.data.inventoryCount)}</TableColumn>
</TableRow>
);
}
}
推荐答案
您应该可以使用 setInterval
constructor() {
super();
// ... existing constructor code
this.loadData = this.loadData.bind(this)
}
loadData() {
ajax(this.state.url, {
success: data => {
console.log(data);
this.setState({data: data.data});
}
}
}
componentDidMount() {
this.loadData();
setInterval(this.loadData, 180000); // 3 minutes in milliseconds. 3*60*1000
}
这篇关于如何在React JS中进行Ajax调用自动刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文