react-native - 数据更改后如何在本机中刷新内容
问题描述
我正在使用 FlatList,在这个 FlatList 中我可以删除任何项目,但删除后,即使我使用了 componentDidMount() 也不会更新!此外,当我尝试向我的 FlatList 添加一个项目时,它不会出现..我总是需要重新加载我的应用程序以获取我的更改
constructor() {
super()
this.state = {
associations: [],
associations2: []
}
}
componentDidMount(){
this.getAll();
}
getAll =async ()=>{
fetch("http://192.168.1.100:8000/association/trouver/benevole/"+id, {method: 'GET',headers:headers })
.then(response => response.json())
.then(data =>{
for(var i=0; i<data.length ; i++){
this.state.associations.push(data[i]);
}
this.setState({associations2:this.state.associations}) })
}
quitter = async(id) => {fetch("http://192.168.1.100:8000/benevole/supprimer/"+idBenevole+"/association/"+id, {method: 'PUT',headers: headers }).then(response => response.json())
.then(data => {
if (data['state'] === "non") {
Toast.show({
text: "Erreur de supression"
type: "warning"})}
else {
Toast.show({
text: "Supression avec succée",
type: "success",
duration: 4000 })}})
this.getAll();
}
render() {
return (
<Container style={styles.container}>
<Content padder style={{ marginTop: 0 }}>
{this.state.associations2.length!== 0 ?
<FlatList data={this.state.associations2}
extraData={this.state.associations2}
keyExtractor={(item, index) => String(index)}
renderItem={({item}) => {
return (
<Card style={styles.mb}>
<CardItem bordered>
<Left>
<Thumbnail source={{uri:`api/${item.imageAssociation}`}}/>
<Body>
<Text style={styles.nomAssociation}>{item.nom.toUpperCase()}</Text>
<Text note>{item.createdAt.substring(0, 10)}</Text>
</Body>
</Left>
</CardItem>
</Card>
);
}}
/>:null
}
{this.state.associations2.length== 0 ?
<Text>Vous n'êtes pas encore membre dans des associations</Text>:null
}
</Content>
</Container>
);
}
我希望我的 FlatList 在我删除一个项目或添加一个项目时得到更新,但它甚至不会改变数据!
解决方案
我会改变几件事:状态应该被视为不可变的,这意味着:
// change those lines
for(var i=0; i<data.length ; i++){
this.state.associations.push(data[i]);
}
// to this
const { associations } = this.state;
for(let i = 0; i < data.length ; i++) {
this.setState({ associations: [ ...associations, data[i]] })
}
// also add this to your state
...
this.state = { extraData: false }
...
// whenever you change the associations2 array do this
const { extraData } = this.state;
this.setState({ associations2: this.state.associations, extraData: !extraData });
// in your FlatList
<FlatList extraData={this.state.extraData} />
并且请不要在您的 FlatList 中使用 index 作为键
推荐阅读
- php - Woocommerce 购物车商品折扣在结账时重置
- android - 谁用 Expo 编译应用程序
- razor-pages - 修复使用 sendgrid 发送验证电子邮件时剃刀页面中的错误 OperationCanceledException
- angular - 根据选中的选择框动态添加选择框和文本框的删除和获取数据
- msbuild - 错误 CS0012:“对象”类型是在未引用的程序集中定义的。您必须添加对程序集 'netstandard, Version=2.0.0.0 的引用
- ruby-on-rails - 将数组数组拆分,将 [0] 拆分为一个,将 [1] 拆分为另一个
- ionic-framework - 无法在 Ionic 的 For 循环中正确设置变量
- kubernetes - Kubernetes/Helm:部署多个 pod,每个 pod 都有其适当的参数
- php - 为什么图像路径没有保存在数据库中?
- python - 从函数返回表达式总和的pythonic方式是什么?