我正在使用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在删除项目或添加项目时得到更新,但数据甚至都不会更改!
答案 0 :(得分:0)
我会改变的几件事: 该状态应视为不可变的,这意味着:
// 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中使用索引作为键