简体   繁体   中英

shuffle function called every time state is updated?

The problem simply is, i have a shuffle function that shuffles array of numbers, the numbers rendered as cards in a deck, the app is simple, it needs when clicking two cards with same number, they get the same color.

so i created a state which is an array which receives only two cards to compare, once comparing is complete, the array length returns to 0 then push two cards again and so on.

now the problem is shuffle function works again and again every time state is updated and this makes cards re-render every time with different numbers(shuffled)

code:

  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;

you can use useEffect:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM