繁体   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