javascript - 如何通过状态传递数组项

标签 javascript arrays reactjs

我正在制作纸牌游戏,并希望 playCard 在数组中包含先前的纸牌和附加的纸牌。目前,当我尝试使用玩家手上的 pop 或 splice 时,它​​会从玩家手数组中取出这些卡并将它们放入 playCard 数组中,但是当player2 尝试添加到 playCard 数组时,它会覆盖它并且里面只有player2 卡。这就是我创建卡片并发牌的方式:

  this.state = {
            deck: [],
            player1: [],
            player2: [],
            player3: [],
            player4: [],
            playCard: [],

        }

        this.makeCards(); 
        this.shuffle();

    }

    makeCards = () => {
        const suits = ['Hearts', 'Spades', 'Clubs', 'Diamonds']
        const values = ['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King']


        for (let suit in suits){
            for (let value in values) {
                this.state.deck.push(<span className='cards' key={value+suit}>{values[value]}</span>);
            }
        }

        return this.deck
    }

    deal = () => {
            this.setState({ player1: this.state.deck.filter((cards, index) => {
                    return index < 13 ? cards : null
                }) 
            }) 
            this.setState({ player2: this.state.deck.filter((cards, index) => {
                    return index >= 13 && index < 26 ? cards : null
                }) 
            }) 
            this.setState({ player3: this.state.deck.filter((cards, index) => {
                    return index >= 26 && index < 39 ? cards : null
                }) 
            }) 
            this.setState({ player4: this.state.deck.filter((cards, index) => {
                    return index >= 39 && index <= 52 ? cards : null
                }) 
            }) 
    }

chooseCard函数将player1数组中的第一张牌放入playCard,但是当player2turn发生时,它会更改为player2数组中的一张牌。

 choseCard(){
        this.setState(() => ({playCard: this.state.player1.splice(0,1)}))

    }
    player2turn() {

        this.setState(() => ({playCard: this.state.player2.splice(0,1)}))
        //I need to filter player2 array to find card value in playCard
        //if it has that then push to this.state.playCard
        //Player 3 sorts through array to find card etc....
    }

我知道现在没有发生任何过滤,我只想将player2添加到playCard数组中。我该如何做到这一点,同时仍然从玩家阵列中取出卡牌?

最佳答案

this.setState(({ playCard, player2 }) => {
  return {
   playCard: [...playCard, ...player2.slice(0, 1)],
   player2: [...player2.slice(1, player2.length - 1)],
  };
});

将先前的状态与新的状态结合起来,并且不要改变它。如果您还需要更改player2,只需根据上一个状态创建一个新数组,而不需要第一张卡。

关于javascript - 如何通过状态传递数组项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58884409/

相关文章:

javascript - REGEX 在 javascript 中查找选项标签

arrays - 是否可以在 Matlab 中定义一个数组来保存数学运算符 [+ - */]?

C++ 数组编号从大到小

reactjs - 我可以从 componentDidMount 调用 onChange 事件吗

reactjs - React - 无法检索表单中文本字段的最新值

javascript - 如何循环所有具有键名的数据,包括一些文本

javascript - 创建标签的输入字段

javascript - 为什么这在 Firefox 中不起作用?

java - 如何使用 Jersey 将嵌套列表编码为 JSON?我得到一个空值数组或一个包含数组的单元素字典数组

javascript - 将视频流 JavaScript 代码传输到 React (ML5)