最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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} />;
};

发布评论

评论列表(0)

  1. 暂无评论