react-native - React Native 组件不重新渲染
问题描述
由于某种原因,该组件没有在 setDependent 上重新渲染,我添加了 setPerson 并且控制台确实记录了该项目而没有删除该项目,但没有更新该组件。请参阅下面的代码,截至目前,从服务器加载没有问题,但在删除时它确实发送了删除命令,但列表没有重新渲染,“人”仍然列在 FlatList 上
const RemoveDependent = ({ onPress }) =>
(
<TouchableWithoutFeedback onPress={onPress}>
<View style={{
backgroundColor: colors.dangerLight,
//height: 70,
width: 70,
//borderRadius: 35,
right:-5,
justifyContent: 'center',
alignItems: 'center'
}}>
<MaterialCommunityIcons name="trash-can" size={30} style={{ color: colors.white }} />
</View>
</TouchableWithoutFeedback>
)
function FamilyScreen(props) {
const [person, setDependent] = useState(dependents);
const handleRemove = onDependent => {
console.log(person.filter(d => d.id !== onDependent.id));
setDependent(person.filter((d) => d.id !== onDependent.id));
}
return (
<View style={{ backgroundColor: colors.white, flex: 1 }}>
<Image
source={require('../assets/familyBg.jpeg')}
style={styles.image}
resizeMode="cover"
/>
<View style={styles.details}>
<RevText style={styles.title}>Family Plan</RevText>
<RevText style={styles.description}>Description here</RevText>
</View>
<FlatList
data={dependents}
keyExtractor={personal => personal.id.toString()}
renderItem={({ item }) => (
<ListItem
onPress={() => handleRemove(item) }
title={item.name}
subTitle={item.type}
image={item.image}
renderRightActions={() => (<RemoveDependent onPress={() => handleRemove(item)} />) }
ItemSeparatorComponent={() => (<View style={{ width: '96%', left: 5, borderBottomColor: 'red', borderBottomWidth: 1 }} />)}
/>
)}
/>
</View>
);
}
Object {
"id": 1014,//REMOVED ID WHEN CLICKED
"image": 19,
"name": "Person 1",
"type": "Child",
}
Array [ //NEW ARRAY
Object {
"id": 1015,
"image": 19,
"name": "PERSON 2",
"type": "Child",
},
Object {
"id": 1016,
"image": 19,
"name": "PERSON 3",
"type": "Child",
},
Object {
"id": 1017,
"image": 19,
"name": "PERSON 4",
"type": "Child",
},
]
解决方案
此代码的主要问题是您正在直接更改状态对象。您应该将所有状态对象视为不可变的。
改变
setDependent(person.filter((d) => d.id !== onDependent.id));
和
setDependent([...person.filter((d) => d.id != onDependent.id)]);
推荐阅读
- android - 更改 Recycleradapter 的 Alpha/Opacity
- c# - C# 将双精度值 0.0 更改为 0
- shiny - selectInput 类别选择
- parsing - 在 ClojureScript 程序中使用 Cuerdas 解析十进制数
- javascript - MatTableDataSource:更改filterPredicate后刷新表格内容而不更改过滤器
- c# - 将Postman转换为C#代码我附上两张Postman的图片
- databricks - 如何从 Databricks mnt 目录中删除文件夹/文件
- css - 我无法理解以下示例的溢出-x 和溢出-y 属性
- c# - 通过 LINQ to SQL 绑定数据时如何在 C# 中向 DataGridView 添加行
- java - java.io.IOException:在 Andoid 上使用相机时权限被拒绝?