[英]While changing one state in React both states are getting changed
I am trying to change one state but while doing that somehow my other state is also getting changed and I can't find the problem in this what should I do?我正在尝试更改一个 state 但是在这样做的同时,我的另一个 state 也正在更改,我找不到这个问题我该怎么办? here is my code:这是我的代码:
import React, {useState } from 'react'
//style = {{margin : '50px', minWidth : '1200px' , minHeight : '500px'}
const Container = ()=>{
const [arr , setArray] = useState([])
const [steps , setSteps] = useState([[]]);
const createArray = () =>{
let array = []
let i = 0;
while (i <60){
let number = Math.random()*100;
array.push(number);
i++;
}
return array;
}
const BubbleSort = (array) =>{
let funarray = new Array();
funarray = array ;
for (let i = 0 ; i < funarray.length-1 ; i++){
for(let j = 0 ; j < funarray.length-1 ; j++){
if(funarray[j]>funarray[j+1]){
[funarray[j],funarray[j+1]] = [funarray[j+1],funarray[j]]
setSteps([...steps,funarray]);
}
}
}
}
const handleCreateNewData = ()=>{
let newarr = createArray();
setArray([...newarr]);
}
const handleBubbleSort = ()=>{
BubbleSort(arr);
}
return(
<div className="container " style = {{margin : '50px ', minWidth : '1200px' , minHeight : '500px'}}>
<div className="row">
<div className="col s2 " style = {{margin : '20px' , padding : '20px'}}>
<div className="row" ><a class="waves-effect waves-light btn green" onClick = {handleCreateNewData}>Create New Array</a></div>
<div className="row"><a class="waves-effect waves-light btn black" onClick = {handleBubbleSort}>BubbleSort</a></div>
<div className="row"><a class="waves-effect waves-light btn black">button</a></div>
<div className="row"><a class="waves-effect waves-light btn black">button</a></div>
<div className="row"><a class="waves-effect waves-light btn black">button</a></div>
<div className="row"><a class="waves-effect waves-light btn black">button</a></div>
</div>
<div className="col s9 grey">
<div style = {{minWidth : '1000px' , minHeight : '500px'}}>
{arr.map((val , index)=>(
<div>
<div style = {{height : '1px'}}></div>
<div className="bar black" style = {{height : '7px' , width : val*8}}> </div>
<div style = {{height : '1px'}}></div>
</div>
)
)
}
</div>
</div>
</div>
</div>
)
}
export default Container ;
I m trying to create an array of arrays in steps in which after each pass the new array will be saved but while doing that my arr is also changing.我正在尝试创建一个 arrays 数组,在每次通过后,新数组将被保存,但同时我的 arr 也在改变。
I think your mistake is in the line:我认为你的错误在于:
funarray = array
of Bubblesort.冒泡排序。 Should work with:应该与:
funarray = [...array]
Otherwise you are modifying your original array, to which you are passing the reference.否则,您将修改原始数组,并将引用传递给该数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.