reactjs - FlatList 更新错误的元素
问题描述
我已经根据最后收到的消息更新了我的平面列表,这些消息呈现为平面列表的组成部分。出于这个原因,我在下面的代码中进行了编码,但是这段代码总是更新 flatlist 的最后一项而不是它的键。
const [lastMessage, setlastMessage] = useState([
{ key: "1", text: "j1" },
{ key: "2", text: "j2" },
{ key: "3", text: "j3" },
]);
const goBack = (id, data) => { // Here is the change statement that update flatlist.
let result = lastMessage.filter((obj) => {
return obj.key != id;
});
result.push({ key: id, text: data });
setlastMessage(result);
};
平面列表:
<FlatList
contentContainerStyle={{
width: "100%",
paddingBottom: 200,
}}
keyExtractor={(item) => item.key}
data={lastMessage}
extraData={lastMessage}
renderItem={({ item }) => {
return (
<TouchableOpacity
activeOpacity={0.55}
onPress={() =>
navigation.navigate("ChatScreen", {
ChatRoomID: item.key,
onGoback: goBack, // Here is the reference of function
})
}
>
<ChatCard text={item.text} />
</TouchableOpacity>
);
}}
/>
聊天画面:
async function handleSend(messages) {
const writes = messages.map((m) => {
chatsRef.add(m);
goBack(ChatRoomID, m["text"]); // i give value to parent from that
});
await Promise.all(writes);
}
解决方案
使用Array.map
而不是filter
.
const goBack = (id, data) => {
// Here is the change statement that update flatlist.
let result = lastMessage.map(obj =>
obj.key === id ? { key: id, text: data } : obj
);
setlastMessage(result);
};
推荐阅读
- csv - 如何在摄取期间在 marklogic 中添加一列?
- react-native - React Native 代码在 iPhone X 模拟器上的行为不同
- xslt-2.0 - 将下拉菜单的默认值设置为否
- travis-ci - 在 travis-ci 中的阶段之间传递信息
- ios - ios全屏背景图片
- javascript - 如何链接到Angular中同一页面上的锚点
- ios - UITableView,点击按钮自动调整单元格高度
- python - 如何检查另一个程序中的任务是否已完成?
- spring - Spring Boot:Spring 数据 jpa + Mariadb
- macos - 在 Mac 上安装 kubectl 时如何解决 localhost:8080 not found 问题?