我的技能很基本,而且我是React native的新手,我想做的就是将帖子限制在12个,并且当用户滚动时会自动加载更多帖子。
我的代码:
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
in构造函数
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}
/>
...
);
}
希望这会有所帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句