我想简单地删除切换到页面时状态中存在的dataSource。因为每次获取数据时,所有先前的响应仍然存在于状态中。每次附加数据,但我想在第一次打开页面时从dataSource开始。
因此,首先我将构造函数中的dataSource和response设置为null。
constructor(props) {
super(props);
this.fetchData = this._fetchData.bind(this);
this.state = {
dataSource: null,
response: null,
};
}
这是我通过api获取数据并获得响应的方式。
_fetchData(callback) {
...
fetch(`http://www.example.com/apifetch.php?etc`)
.then(response => response.json())
.then(callback)
.catch(error => {
console.error(error);
});
}
在componentDidMount中,我将json响应置于具有setState的状态。
componentDidMount() {
this.fetchData(responseJson => {
let ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2,
});
const data = responseJson.results;
console.log(responseJson);
this.setState({
dataSource: ds.cloneWithRows(data),
isLoading: false,
_data: data,
_dataAfter: responseJson.after,
response: data,
});
});
}
当我渲染this.state.dataSource时,它会显示新的和之前的所有响应。现在,第一次删除dataSource的最佳方法是什么,以便所有以前的数据都消失了,如何完成(不使用像Redux这样的软件包)?
更新 我特意搜索的是一种方式,当一个页面被重新渲染并初始化一个新的ListView.DataSource时,将删除该状态中存储的先前DataSource。
现在,每次渲染后,多个dataBlob都会存储在该状态中。
{"_dataBlob":{"s1":[{"id":"1","key_id":"1","title":"title","image":{"uri":"http://www.example.com/1.jpg"}}]},{"id":"2","key_id":"2","title":"title","image":{"uri":"http://www.example.com/2.jpg"}}]}"_dirtyRows":[[true,true]],"_dirtySections":[false],"_cachedRowCount":2,"rowIdentities":[["0","1"]],"sectionIdentities":["s1"]}
{"_dataBlob":{"s1":[{"id":"3","key_id":"3","title":"title","image":{"uri":"http://www.example.com/3.jpg"}}]},{"id":"2","key_id":"2","title":"title","image":{"uri":"http://www.example.com/4.jpg"}}]}"_dirtyRows":[[true,true]],"_dirtySections":[false],"_cachedRowCount":2,"rowIdentities":[["0","1"]],"sectionIdentities":["s1"]}
这样,当用户连续访问不同的页面时,性能会降低。是否有解决方案,或者这仅仅是使用ListViews的缺点,例如FlatLists?