簡體   English   中英

每次更新 state 時都會調用隨機播放 function 嗎?

[英]shuffle function called every time state is updated?

問題很簡單,我有一個洗牌 function 洗牌數組,數字呈現為一副牌中的牌,應用程序很簡單,當點擊兩張相同號碼的牌時,它們需要相同的顏色。

所以我創建了一個 state 這是一個數組,它只接收兩張卡進行比較,一旦比較完成,數組長度返回 0 然后再次推送兩張卡,依此類推。

現在問題是洗牌 function 每次更新 state 時都會一次又一次地工作,這使得卡片每次都用不同的數字重新渲染(洗牌)

代碼:

  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;

你可以使用useEffect:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM