2 回答
TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超13個(gè)贊
你可以使用useMemo鉤子。
const shuffle = (arr) => {
//shuffle logic here
}
const shuffledCards = React.useMemo(() => {
const numbers = [1, 2, 3, 1, 2, 3];
return shuffle(numbers);
}, [])
return (
<cards shuffledCards={shuffledCards} />
)
TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
您的函數(shù)正在重新定義shuffleCards每次渲染的數(shù)組。如果將陣列置于狀態(tài),它將是穩(wěn)定的。
numbers將組件和外部組件定義shuffle為初始狀態(tài)和效用函數(shù)
const numbers = [1, 2, 3, 1, 2, 3];
const shuffle = array => {
// shuffle logic
};
組件邏輯:初始化狀態(tài)并使用效果在組件掛載時(shí)對(duì)數(shù)組進(jìn)行洗牌
const CardShuffler = () => {
const [shuffledCards] = useState(shuffle(numbers)); // initialize state
return <Cards shuffledCards={shuffledCards} />;
};
添加回答
舉報(bào)
