我正在从 api 获取数据,每 15 个项目获取更多数据。但是,当没有更多数据时,它仍在尝试获取更多数据,并给出下一个项目不存在或只是从 0 循环项目的错误。如何停止从数据库中获取最后一项的数据?这是我的代码:
export default class One extends React.PureComponent {
constructor(props) {
super(props);
this.fetchMore = this._fetchMore.bind(this);
this.fetchData = this._fetchData.bind(this);
this.state = {
isLoading: true,
isLoadingMore: false,
_data: null,
_dataAfter: '',
accessToken: "",
};
}
async componentWillMount() {
try {
let accessToken = await AsyncStorage.getItem(ACCESS_TOKEN).then(JSON.parse);
if(!accessToken) {
this.redirect('login');
} else {
this.setState({accessToken: accessToken})
}
} catch(error) {
console.log("Something went wrong");
this.redirect('login');
}
this.fetchData(responseJson => {
const data = responseJson;
this.setState({
isLoading: false,
_data: data,
_dataAfter: responseJson.after,
});
});
}
_fetchData(callback) {
const params = this.state._dataAfter !== ''
? `&after=${this.state._dataAfter}`
: '';
fetch(`https://mywebsite.com/posts?limit=15${params}`,
{
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': "Bearer " + this.state.accessToken.token,
}
})
.then(response => response.json())
.then(callback)
.catch(error => {
console.error(error);
});
}
_fetchMore() {
this.fetchData(responseJson => {
const data = this.state._data.concat(responseJson);
this.setState({
isLoadingMore: false,
_data: data,
_dataAfter: responseJson.after,
});
});
}
render() {
if (this.state.isLoading) {
return (
<View style={styles.container}>
<ActivityIndicator size="large" />
</View>
);
} else {
return (
<FlatList
numColumns={1}
data={this.state._data}
renderItem={({item}) => {
return (
<View>
<Text>
{item.name}
</Text>
</View>
);
}}
onEndReached={() =>
this.setState({ isLoadingMore: true }, () => this.fetchMore())}
ListFooterComponent={() => {
return (
this.state.isLoadingMore &&
<View style={{ flex: 1, padding: 10 }}>
<ActivityIndicator size="small" />
</View>
);
}}
keyExtractor={(item, index) => index}
/>
);
}
}
}
只需制作参数即可注意到没有剩余项目
将状态更改为
this.state = {
isLastData: false, // this new var
isLoading: true,
isLoadingMore: false,
_data: null,
_dataAfter: '',
accessToken: "",
};
让抓取更像这样
_fetchMore() {
this.fetchData(responseJson => {
const data = this.state._data.concat(responseJson.children);
this.setState({
isLastData: data.length > 0 ? false : true,
isLoadingMore: false,
_data: data,
_dataAfter: responseJson.after,
});
});
}
将逻辑添加到 onEndReach
onEndReached={
() => {
if (! this.state.isLastData) {
this.setState({ isLoadingMore: true }, () => this.fetchMore())
}
}
}