我使用的是 setInterval
的组合,位于我的 componentDidMount
函数中,该函数从 API 获取数据并为获取的数据设置状态,并将其显示在我的 react native map 。问题在于,将 setInterval
与 setState
一起使用的成本太高,因为 map 必须每 5 秒重新渲染一次。
componentDidMount() {
this.interval = setInterval(() => {
api.getData().then((res) => {
this.setState({
data: res
})
});
}, 5000);
}
我对此进行了研究,发现我应该使用 houldComponentUpdate
,但我无法让它工作,因为 map 无法正确渲染,在不应该渲染时渲染并且不渲染当它应该的时候。
shouldComponentUpdate(nextProps, nextState) {
for(var i = 0; i < this.state.data.length; i++) {
if(this.state.data[i].value !== nextState.data[i].value) {
return true;
}
}
return false;
}
我正在将我拥有的数据状态与下一个状态的数据进行比较,即 this.state.data !== nextState.data
,如果是,我返回 true。
我是否正确地处理了这个问题,因此这是 ShouldComponentUpdate 应该解决的问题,而我只是没有正确编写该函数,或者我应该专注于不同的解决方案?
最佳答案
shouldComponentUpdate
中的内容是:
- 当组件收到新的
props
时,您还会停止重新渲染 - 如果
nextState
具有不同的长度,您的方法不会检查它。在这种情况下,我们总是想要重新渲染
shouldComponentUpdate(nextProps, nextState) {
// Just an example, you need compare actual parameter which inside props
if (this.props !== nextProps) {
return true;
}
if (this.state.data.length !== nextState.data.length) {
return true;
}
for (var i = 0; i < this.state.data.length; i++) {
if (this.state.data[i].value !== nextState.data[i].value) {
return true;
}
}
return false;
}
关于javascript - react native : How to go about using ShouldComponentUpdate with setInterval and setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49501982/