javascript - How to shuffle an array once in functional react component? - Stack Overflow

I am creating a memory game, i have a shuffle function that shuffles an array of numbers, these numbers

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 0
Add a ment  | 

2 Answers 2

Reset to default 4

You 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信