Reactjs 洗牌反应中的奇怪行为
在我的React应用程序中,我为2套不同的牌组调用了2次shuffle,但shuffle总是给出2套完全相同的结果,有人能帮我修复它吗Reactjs 洗牌反应中的奇怪行为,reactjs,shuffle,Reactjs,Shuffle,在我的React应用程序中,我为2套不同的牌组调用了2次shuffle,但shuffle总是给出2套完全相同的结果,有人能帮我修复它吗 class PairThemUp extends React.Component{ constructor(props){ super(props); this.state={ cards1:[], cards2:[], } } shuffl
class PairThemUp extends React.Component{
constructor(props){
super(props);
this.state={
cards1:[],
cards2:[],
}
}
shuffleCards=()=>{
const cards=this.props.selectedCards
const cards1=shuffle(cards)
const cards2=shuffle(cards)
this.setState({cards1, cards2})
const id1=cards1.map(c=>c.id)
const id2=cards2.map(c=>c.id)
console.log(id1, id2)
}
在我再次运行shuffleCards函数之前,shuffle会给出两组相同的结果。这是我的洗牌功能
export const shuffle=(a)=> {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
cards
、cards1
和cards2
在示例中都指向同一数组,因为JavaScript通过引用传递数组
结果是,每次调用shuffle
,都会修改并返回传递给函数的基础数组,因此,任何指向先前调用shuffle
结果的变量都会反映最近被洗牌的数组
修复方法是在洗牌
中创建阵列的副本,以便卡
、卡1
、和卡2
都指向不同的阵列:
let shuffle = (a) => {
let newArr = [].concat(a); // create new array
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[newArr[i], newArr[j]] = [newArr[j], newArr[i]];
}
return newArr;
};