如何通过状态传递数组项

时间:2019-11-15 20:41:50

标签: javascript arrays reactjs

我正在制作纸牌游戏,希望playCard在阵列中包含以前的纸牌和其他纸牌。当前,当我尝试使用玩家手牌的弹出或熔接时,将从玩家手牌中取出这些纸牌并将其放入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
                }) 
            }) 
    }

choseCard函数将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数组中。在仍从播放器阵列中取出卡的同时,我该怎么做?

2 个答案:

答案 0 :(得分:1)

您应该使用状态值的副本进行操作。否则,您将直接处理阵列。尝试这样的事情。它将创建一个副本。处理阵列,然后将它们放回原状。

choseCard(){
  let player1 = [ ...this.state.player1 ]
  let playCard = player1.splice[0,2]
  this.setState(() => ({player1, playCard}))
}
player2turn() {
  let player1 = [ ...this.state.player1 ]
  let playCard = [ player1.pop() ]
  this.setState(() => ({player1, playCard}))
  //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....
}

答案 1 :(得分:1)

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

将先前的状态与新的状态组合起来,不要对其进行突变。如果还需要更改player2,则只需根据先前状态创建一个新阵列,而无需第一张卡。