【发布时间】:2018-01-27 14:09:34
【问题描述】:
我正在尝试实现分页。我在每个 fetch request 中获取 10 个项目的数组,并将它们保存在 listview 的 onEndReached 调用时的状态中,我正在获取下一个项目,依此类推。
我的问题是,当我获取下一个项目数组时,之前获取的项目以它们正在消失的状态保存。当我更新状态时,只显示当前获取的项目。
我希望上一次提取的项目在下一次提取时不会消失。我可以将新项目附加到现有状态吗?如果是,我该怎么做?
如果我出错了,那么如何使用我不知道的任何 react native 组件来实现这一点?
这是我的代码
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)}
/>
【问题讨论】:
-
是的,您可以更新状态,显示您目前正在尝试的代码。
-
所以基本上你需要保存你的项目而不是覆盖。为此,您可以将现有状态缓存在某种基本状态中,然后将新项目附加到基本状态中。
-
是的,您可以将数据添加到前一个,只需将获取的值添加或附加到前一个。
-
感谢您的回复,您能否通过代码给出一些提示。我将首先用代码更新我的问题。
-
我现在更新了,抱歉代码太长了,我缩短了。
标签: react-native state react-native-android react-native-listview