reactjs - How i can limit the items in the FlatList and add load more?
问题描述
My skills is basic, and i'm newbie in React native, what i want to do is limit the posts in 12 and when the user scroll automatically load more posts.
My Code:
export default class Posts extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,};}
componentDidMount() {
return fetch(ConfigApp.URL+'json/data_posts.php')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataPosts: responseJson
}, function() {
});
})
.catch((error) => {
});}
render() {
return (
<FlatList
data={ this.state.dataPosts }
numColumns={2}
renderItem={({item}) =>
<TouchableOpacity activeOpacity={1} style={{flex: 1}}>
<View style={{margin: 5, marginLeft: 4}}>
<ImageBackground source={{uri: ConfigApp.IMAGESFOLDER+item.post_image}}>
<LinearGradient colors={['rgba(0,0,0,0.3)', 'rgba(0,0,0,0.8)']}>
<Text numberOfLines={2}>{item.post_title}</Text>
</LinearGradient>
</ImageBackground>
</View>
</TouchableOpacity>
}
keyExtractor={(item, index) => index}
/>
);}}
解决方案
如果您的要求是将现有列表从已提取的数据中追加到 12 块中,那么您可以考虑使用以下策略来处理滚动onEndReached
并onEndThreshold
一次添加 12 条记录。
在构造函数中设置当前page
数字0
constructor(props){
super(props);
this.state = {
... ,
page: 0,
posts: []
}
}
在内部componentDidMount
,您需要从服务器中提取所有数据并将其存储在本地状态(您当前正在执行的操作)中,然后调用将读取前 12 条记录的函数。
componentDidMount() {
return fetch(ConfigApp.URL+'json/data_posts.php')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
page: 0,
dataPosts: responseJson
}, function() {
// call the function to pull initial 12 records
this.addRecords(0);
});
})
.catch((error) => {
});
}
现在添加将添加记录的功能this.state.dataPosts
addRecords = (page) => {
// assuming this.state.dataPosts hold all the records
const newRecords = []
for(var i = page * 12, il = i + 12; i < il && i <
this.state.dataPosts.length; i++){
newRecords.push(this.state.dataPosts[i]);
}
this.setState({
posts: [...this.state.posts, ...newRecords]
});
}
现在添加滚动处理程序
onScrollHandler = () => {
this.setState({
page: this.state.page + 1
}, () => {
this.addRecords(this.state.page);
});
}
渲染功能
render() {
return(
...
<FlatList
...
data={this.state.posts}
renderItem={({item}) => ... }
keyExtractor={(item, index) => index}
onEndReached={this.onScrollHandler}
onEndThreshold={0}
/>
...
);
}
希望这会有所帮助!
推荐阅读
- javascript - 如何修复“未捕获的 TypeError:无法在 'URL' 上执行 'createObjectURL':未找到与提供的签名匹配的函数..”
- python - 捕获设备附加分离通知
- java - Web 服务器启动时将 JSON 文件转换为 java 对象
- javascript - 如何修复 React Native 中的导航问题(TypeError: undefined is not an object(evalating '_this.props.navigation)
- mapbox-android - Mapbox 交通插件错误
- angular - 下拉菜单未显示加载值
- mongodb - 提高猫鼬种群性能
- ios - 如何获取集合视图中所选项目的位置?
- python - 从 txt 文件中的数组发送单个电子邮件
- python - 使用 Python 将输出打印到 CSV 文件并对其进行格式化