我正在尝试实施分页。我在每个fetch request
中获取10个项目的数组,并在列表视图的onEndReached
将被调用时保存它们状态我将获取下一个项目,依此类推。
我的问题是,当我获取下一个项目数组时,之前获取的项目将保存在状态正在消失。当我更新状态时,只显示当前已获取的项目。
我希望以前提取的项目不会在下次提取时消失。我可以将新项目附加到现有状态吗?如果是,我该怎么办?
如果我出错了,那么如何使用我不知道的本地反应组件来实现这一目标呢?
这是我的代码
constructor(props) {
super(props);
this.state = {
next: "",
qwerty: []
};
this.fetchData = this.fetchData.bind(this);
}
fetchData() {
return fetch('https://shopconapp.herokuapp.com/api/pagination/')
.then((response) => response.json())
.then((responseData) => {
if (!responseData) {
navigate("Login");
} else {
console.log(responseData);
let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.setState({
nexturl: responseData.next,
qwerty: ds.cloneWithRows(responseData.results.post),
});
}
})
}
_onEndReached(){
url = this.state.nexturl;
return fetch(this.state.nexturl)
.then((response) => response.json())
.then((responseData) => {
if (!responseData) {
navigate("Login");
} else {
console.log(responseData);
let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.setState({
nexturl: responseData.next,
qwerty: ds.cloneWithRows(responseData.results.post),
});
}
})
}
<ListView
dataSource={this.state.qwerty}
onEndReachedThreshold={2}
onEndReached={this._onEndReached.bind(this)}
/>
答案 0 :(得分:2)
将posts
添加到您的州
this.state = {
next: "",
posts : []
qwerty: []
};
用于fetchData方法保存帖子的状态
fetchData() {
return fetch('https://shopconapp.herokuapp.com/api/pagination/')
.then((response) => response.json())
.then((responseData) => {
if (!responseData) {
navigate("Login");
} else {
console.log(responseData);
let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.setState({
nexturl: responseData.next,
posts : responseData.results.post ,
qwerty: ds.cloneWithRows(responseData.results.post),
});
}
})
}
现在在onEndReach
中将新帖子附加到之前的帖子并从州内制作数据来源
_onEndReached(){
url = this.state.nexturl;
return fetch(this.state.nexturl)
.then((response) => response.json())
.then((responseData) => {
if (!responseData) {
navigate("Login");
} else {
console.log(responseData);
let posts = this.state.posts.concat(responseData.results.post);
let ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.setState({
nexturl: responseData.next,
posts : posts ,
qwerty: ds.cloneWithRows(posts),
});
}
})
}
答案 1 :(得分:0)
您可以使用ES6语法更新阵列:
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
nexturl: responseData.next,
qwerty: ds.cloneWithRows([...this.state.qwerty, ...responseData.results.post]),
});