【问题标题】:shuffle function called every time state is updated?每次更新状态时调用的随机播放函数?
【发布时间】:2020-04-14 01:39:42
【问题描述】:

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

所以我创建了一个状态,它是一个只接收两张卡进行比较的数组,一旦比较完成,数组长度返回 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;

【问题讨论】:

    标签: javascript reactjs shuffle


    【解决方案1】:

    你可以使用useEffect:

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

    【讨论】:

      猜你喜欢
      • 2015-11-16
      • 1970-01-01
      • 2020-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-23
      相关资源
      最近更新 更多