[英]Not able to run onEndReached in React Native Flatlist component
[英]onEndReached on flatlist invoked endless [React Native]
我正在尝试使用 ReactNative 和 Expo 开发我的第一个应用程序。 但是我对 FlatList 有问题,组件进行了无限调用,但我不在视图的末尾。 第二个问题,可能是相关的,我有多个屏幕,当我在另一个屏幕上时,无限的 api 调用不会停止..
一个主意 ?
编码 :
import * as React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import * as WebBrowser from 'expo-web-browser';
import { RectButton, ScrollView, FlatList } from 'react-native-gesture-handler';
import UserRankingList from '../components/UserRankingList';
export default class RankingsScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
users: []
};
console.log("constructor")
}
componentDidMount() {
console.log('componentDidMount')
// Toggle the state every second
this.getUsers(0)
}
getUsers(page) {
console.log('getUsers')
console.log('make request with page ' + page)
return fetch('https://myapi/users/' + page + '/10/', {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-Instance': 'myinstance'
}
})
.then(response => response.json())
.then(responseJson => {
let users = this.state.users
this.setState({
loading: false,
users: [...this.state.users, ...responseJson]
})
})
.catch(error => {
console.error(error);
});
}
loadMoreUser() {
console.log('loadMoreUser')
if (this.state.users.length >= 10 && (this.state.users.length % 10) === 0 && !this.state.loading) {
let page = this.state.users.length / 10
this.getUsers(page)
}
}
render() {
console.log('render')
return (
<View>
<FlatList
contentContainerStyle={{flexGrow:1}}
data={this.state.users}
refreshing={this.state.loading}
keyExtractor={(item) => item.userid}
onEndReached={this.loadMoreUser()}
onEndReachedThreshold={0.1}
renderItem={({ item }) => (
<UserRankingList user={item}/>
)}
/>
</View>
);
}
}
function getRanking() {
return fetch('https://myapi/users/0/10/', {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-Instance': 'myinstance'
}
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson)
return responseJson;
})
.catch(error => {
console.error(error);
});
}
和输出:
构造函数
使成为
加载更多用户
组件DidMount
获取用户
向页面 0 发出请求
使成为
加载更多用户
获取用户
使用第 1 页提出请求
使成为
加载更多用户
获取用户
用第 2 页提出请求
使成为
加载更多用户
获取用户
用第 3 页提出请求
使成为
加载更多用户
获取用户
用第 4 页提出请求
您应该使用箭头功能。
代替 :
onEndReached={this.loadMoreUser()}
用这个 :
onEndReached={ () => { this.loadMoreUser() } }
和你一样,我必须多读一点文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.