I am creating a memory game, i have a shuffle function that shuffles an array of numbers, these numbers are rendered as cards, the problem is that the cards are shuffled every time state changed, i need to only initialize my ponent with a shuffled array that persists even state is changed!
i tried useEffect
, but it doesn't work, or i couldn't implement it correctly
code:
const numbers = [1, 2, 3, 1, 2, 3];
const shuffle = (arr) => {
//shuffle logic here
}
let shuffledCards;
useEffect(() => {
shuffledCards = shuffle(numbers) // it doesn't help
}, [])
return(
<cards shuffledCards={shuffledCards} />
)
how can i shuffle my array once instead of every time state is changed!
I am creating a memory game, i have a shuffle function that shuffles an array of numbers, these numbers are rendered as cards, the problem is that the cards are shuffled every time state changed, i need to only initialize my ponent with a shuffled array that persists even state is changed!
i tried useEffect
, but it doesn't work, or i couldn't implement it correctly
code:
const numbers = [1, 2, 3, 1, 2, 3];
const shuffle = (arr) => {
//shuffle logic here
}
let shuffledCards;
useEffect(() => {
shuffledCards = shuffle(numbers) // it doesn't help
}, [])
return(
<cards shuffledCards={shuffledCards} />
)
how can i shuffle my array once instead of every time state is changed!
Share Improve this question edited Apr 17, 2020 at 3:12 Code Eagle asked Apr 17, 2020 at 2:53 Code EagleCode Eagle 1,2623 gold badges23 silver badges42 bronze badges 02 Answers
Reset to default 4You can use useMemo
hook.
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} />
)
Your function is redefining your array shuffleCards
each render. If you place the array into state it will be stable.
Define numbers
and shuffle
outside ponent as initial state and utility function
const numbers = [1, 2, 3, 1, 2, 3];
const shuffle = array => {
// shuffle logic
};
Component logic: Initialize state and use the effect to shuffle the array on ponent mount
const CardShuffler = () => {
const [shuffledCards] = useState(shuffle(numbers)); // initialize state
return <Cards shuffledCards={shuffledCards} />;
};
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745308832a4621875.html
评论列表(0条)