首页 > 解决方案 > 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);
  }

标签: reactjsreact-native

解决方案


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

推荐阅读