问题很简单,我有一个随机播放功能,可以随机播放数字数组,
在卡组中显示为卡片的数字,该应用程序很简单,需要单击两张具有相同数字的卡片,它们的颜色相同。
所以我创建了一个状态,该状态是一个仅接收两张卡片进行比较的数组,一旦比较完成,数组长度将返回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;
最佳答案
您可以使用useEffect:
const [cards, setCards] = useState([]);
useEffect(()=>{shuffle()},[cards])