每次状态更新时都会调用随机播放功能吗?

时间:2020-04-14 01:39:42

标签: javascript reactjs shuffle

问题很简单,我有一个随机播放功能,可以随机播放数字数组, 在卡组中呈现为卡片的数字,该应用程序很简单,需要单击两张具有相同数字的卡片,它们的颜色相同。

所以我创建了一个状态,该状态是一个仅接收两张卡进行比较的数组,一旦比较完成,数组长度将返回0,然后再次推送两张卡,依此类推。

现在的问题是,随机播放功能在每次状态更新时都反复起作用,这使得每次使用不同编号(随机播放)重新渲染卡片

代码:

  const icons = [1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 7, 8, 5, 6, 7, 8];

  const shuffle = (cards) => {
    let counter = cards.length;

    // While there are elements in the array
    while (counter > 0) {
      // Pick a random index
      let index = Math.floor(Math.random() * counter);

      // Decrease counter by 1
      counter--;

      // And swap the last element with it
      let temp = cards[counter];
      cards[counter] = cards[index];
      cards[index] = temp;
    }

    return cards;
  }

  const shuffledCards = shuffle(icons);

  const [cards, setCards] = useState([]);
  const [isCorrect, checkCorrect] = useState(false)

  const addCard = (card) => {
    if (cards.length < 2) {
      setCards([...cards, card]);
    }

    if(cards.length === 2) {
      compareCards(cards);
      setCards([]);
     }
  }

  const compareCards = (cards) => {
    if(cards[0] === cards[1] ) {
      checkCorrect(true);
    }
  } 

   return (
    <div className="App">
      <Game shuffledCards={shuffledCards} addCard={addCard} />
    </div>
  );
}

const Game = (props) => {

    const { shuffledCards, addCard } = props;

    return (
        <div className="game">
            <div className="deck">
                {
                    shuffledCards.map((c, i) => {
                        return (
                            <div className="card" key={i} onClick={() => addCard(c)}>{c}</div>
                        );
                    })
                }
            </div>

        </div>
    )
}


export default App;

1 个答案:

答案 0 :(得分:1)

您可以使用useEffect:

const [cards, setCards] = useState([]);
useEffect(()=>{shuffle()},[cards])
相关问题