【问题标题】:Select and deselect multiple items from array从数组中选择和取消选择多个项目
【发布时间】:2020-10-29 13:12:14
【问题描述】:

我在这里有一个 sn-p 代码,其中我有一个数组,其中可能有也可能没有键。当用户按下“朋友”时,他们会将他们添加到列表(数组)中,在那里他们可能会开始与他们聊天(将 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) : 

                }

            }

        }

}

请帮忙!

【问题讨论】:

  • 您已经尝试过什么,在哪里/为什么失败了?
  • @secan - 我确实陷入了循环/if/else 地狱,但下面的代码更优雅,但我仍然遇到同样的问题

标签: javascript arrays reactjs react-native logic


【解决方案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];
    }
  }
}

我使用 typescript 是因为它使事情更容易查看,但您的 JS 代码可能也应该给您一个不错的类型推断。我追求的是可读性而不是性能,但是一旦你了解了这个过程,你就可以轻松地优化上面的脚本。

您应该可以根据我发送给您的内容进行调整以根据您的需要进行调整

【讨论】:

  • 您的代码绝对更优雅,但我仍然得到相同的结果。我有两个朋友,当我点击friendA时-他已添加到gameRoomMembers中,但是当我点击friendB时,friendA被取消选择:/预期(他们都应该处于活动状态,除非我取消选择朋友)
  • 忽略我!这实际上工作得很好,我只是在渲染使用新 this.state.friendsChat 状态的组件时遇到问题谢谢!!!
  • 我很高兴听到@Tyler.G。正如我之前所说,您应该能够调整代码并使其与您的应用程序的结构一起工作。
猜你喜欢
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-22
  • 2012-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多