Javascript React Native Flatlist在拉入时不刷新数据
这是我的帖子页面代码,它在加载时从我的API中获取帖子标题,效果非常好。问题是,一旦加载了它,如果在API中添加了一个新帖子,并且我拉上去刷新它,它就不会得到新帖子,即使我的onRefresh函数可以工作,因为我可以在其中触发一个警报 我可以在加载新帖子后在API中显示它们的唯一方法是重新加载应用程序本身Javascript React Native Flatlist在拉入时不刷新数据,javascript,reactjs,react-native,Javascript,Reactjs,React Native,这是我的帖子页面代码,它在加载时从我的API中获取帖子标题,效果非常好。问题是,一旦加载了它,如果在API中添加了一个新帖子,并且我拉上去刷新它,它就不会得到新帖子,即使我的onRefresh函数可以工作,因为我可以在其中触发一个警报 我可以在加载新帖子后在API中显示它们的唯一方法是重新加载应用程序本身 componentDidMount() { this.fetchData() } constructor(props) { super(props); thi
componentDidMount() {
this.fetchData()
}
constructor(props) {
super(props);
this.state = {
refreshing: true,
data: []
};
}
fetchData = () => {
const url = 'myAPIurl';
fetch(url)
.then(res => {
return res.json()
})
.then(res => {
const arrayData = [...this.state.data, ...res]
this.setState({
data: arrayData,
refreshing: false
});
})
.catch(error => {
console.log(error);
this.setState({ refreshing: false });
});
};
handleRefresh = () => {
this.setState(
{
refreshing: true
},
() => {
this.fetchData();
alert('Pulled Up to Refresh');
}
);
};
render() {
return (
<View>
<FlatList
refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={this.handleRefresh}
/>
}
horizontal={false}
data={this.state.data}
keyExtractor={item => item.id}
renderItem={({ item }) =>
<View>
<Text>{item.title.rendered}</Text>
</View>
}
/>
</View>
);
}
}
componentDidMount(){
this.fetchData()
}
建造师(道具){
超级(道具);
此.state={
令人耳目一新:是的,
数据:[]
};
}
fetchData=()=>{
常量url='myAPIurl';
获取(url)
。然后(res=>{
return res.json()
})
。然后(res=>{
常量arrayData=[…this.state.data,…res]
这是我的国家({
数据:arrayData,
刷新:错误
});
})
.catch(错误=>{
console.log(错误);
this.setState({刷新:false});
});
};
handleRefresh=()=>{
这是我的国家(
{
令人耳目一新:没错
},
() => {
这是fetchData();
警报(“拉上去刷新”);
}
);
};
render(){
返回(
项目id}
renderItem={({item})=>
{item.title.rendered}
}
/>
);
}
}
当我停下来刷新时,我得到一个警告:两个孩子用同一把钥匙。密钥应该是唯一的。这很奇怪,因为每个帖子ID都是唯一的。即使有此警告,API中的新帖子也不会显示,除非我重新加载应用程序。更改您的
handleRefresh
函数,如下所示:
handleRefresh = () => {
this.setState(
{
refreshing: true,
data:[]
},
() => {
this.fetchData();
alert('Pulled Up to Refresh');
}
);
};