【发布时间】:2020-08-04 06:26:06
【问题描述】:
我在页面中有一个组件,我想通过每 30 秒刷新一次组件来获取页面的最新状态,
例如,此数据来自服务器,并且不断添加和删除 id 和名称。我们可以每30秒刷新一次组件Datatable,而不是每次手动刷新页面,以确保我们拥有最新的数据。
我该怎么做。 setInterval 是正确的方法还是 ShouldComponentUpdate 会成功?
编辑:只需要编辑表格而不是整个组件
export class DataTable extends React.Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.context.store.dispatch(getData());
}
componentDidMount(){
this.updateTimer = setInterval(() => this.context.store.dispatch(getData()), 30000);
}
componentWillUnmount(){
clearInterval(this.updateTimer);
}
_getDtableProps() {
const arr = this.props.getData.data;
const data = arr.map((d, i) => {
return {
'id': this.formatPathId(d['id']),
'name': this.formatTime(d['name'])
}
})
return {
data,
dtOptions: {
order: [2, "desc"]
},
columns: [
{
data: 'id',
title: 'Id',
searchable: true
},
{
data: 'name',
title: 'Name',
searchable: true
}
]
}
}
render() {
let tableProps = this._getDtableProps();
return (
<div className={style.container}>
<Table {...tableProps}/>
</div>
);
}
}
【问题讨论】:
-
State and Lifecycle 文档中给出了这种情况的一个很好的例子。该示例实现了一个每秒更新的时钟。它使用
componentDidMount中的setInterval来更新时间。在componentWillUnmount中使用clearInterval删除间隔。
标签: javascript reactjs