FlatList更新错误的元素



我已经根据最后收到的flatlist组件呈现的消息更新了我的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:

<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);
};

try this:

const goBack = (id, data) => {
setlastMessage((value) => {
let result = value.filter((obj) => {
return obj.key != id;
});
return [...result, { key: id, text: data }];
});
};

最新更新