bdr*_*oid 7 reactjs react-native
我的技能很基础,而且我是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}
/>
);}}
Run Code Online (Sandbox Code Playgroud)
如果您的要求是将已拉取的数据中的现有列表附加到 12 个块中,那么您可以考虑以下策略,该策略使用onEndReached和onEndThreshold处理滚动并一次添加 12 条记录。
在构造函数中设置当前page编号0
constructor(props){
super(props);
this.state = {
... ,
page: 0,
posts: []
}
}
Run Code Online (Sandbox Code Playgroud)
在内部,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) => {
});
}
Run Code Online (Sandbox Code Playgroud)
现在添加将从中添加记录的函数 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]
});
}
Run Code Online (Sandbox Code Playgroud)
现在添加滚动处理程序
onScrollHandler = () => {
this.setState({
page: this.state.page + 1
}, () => {
this.addRecords(this.state.page);
});
}
Run Code Online (Sandbox Code Playgroud)
渲染功能
render() {
return(
...
<FlatList
...
data={this.state.posts}
renderItem={({item}) => ... }
keyExtractor={(item, index) => index}
onEndReached={this.onScrollHandler}
onEndThreshold={0}
/>
...
);
}
Run Code Online (Sandbox Code Playgroud)
希望这会有所帮助!
小智 6
您可以在获取数据源中的 jsondata 时添加 slice(start,end) 方法。这个技巧可能会解决你的问题。
dataPosts: responseJson.slice(0,10) 用你的替换这一行。
| 归档时间: |
|
| 查看次数: |
4908 次 |
| 最近记录: |