从数组中选择和取消选择多个项目

时间:2020-10-29 13:12:14

标签: javascript arrays reactjs react-native logic

我在这里有一段代码,其中有一个数组,其中可能有也可能没有键。当用户按下“朋友”时,他们会将他们添加到列表(数组)中,在其中他们可以开始与他们聊天(将3个朋友添加到数组中,然后启动聊天室)。选定的用户可能会打开或关闭。

当前行为: 我可以添加/删除一个人,但不能同时将多个人添加到数组。当我添加一个人时,选择另一个人-第一个人处于“活动状态”,当我删除第一个人时,第二个人会自动变为活动状态

预期的行为: 我希望能够将多个人添加到数组中,然后从数组中删除任何选定的项目

onFriendChatPress = (key) => {
  console.log(key)               // this is my key 'JFOFK7483JFNRW'

 let friendsChat = this.state.friendsChat       // this is an empty array initially []

        if (friendsChat.length === 0) {
            friendsChat.push(key)
        } else {

            // there are friends/keys in the array  loop through all possible items in the array to determine if the key matches any of the keys 

            for (let i = 0; i < this.state.selGame.friends.length; i++) {
   
                // if the key matches, 'toggle' them out of the array

                if (friendsChat[i] === key) {
                    friendsChat = friendsChat.filter(function (a) { return a !== key })
                }
                else {
                   return friendsChat.indexOf(key) === -1 ? friendsChat.push(key) : 

                }

            }

        }

}

请帮助!

1 个答案:

答案 0 :(得分:1)

从您的代码中,我对this.state.selGame.friendsthis.state.friendsChat之间的区别感到很困惑。也许我错过了您的表述。但是,我觉得您的代码对于相对简单的东西似乎过于复杂。这是我要执行的任务:

class Game {
  state = {
    friendsChat: [] as string[],
  };

  onFriendToggle(key: string) {
    const gameRoomMembers = this.state.friendsChat;

    if (gameRoomMembers.includes(key)) {
      this.state.friendsChat = gameRoomMembers.filter(
        (member) => member !== key
      );
    } else {
      this.state.friendsChat = [...gameRoomMembers, key];
    }
  }
}

我使用打字稿是因为它使事情更容易看懂,但是您的JS代码也应该可以为您提供不错的类型推断。我追求性能方面的可读性,但是一旦了解了过程,就可以轻松地优化上面的脚本。

您应该能够按照我发送给您的内容进行调整,使其符合您的需求

相关问题