[英]React state arrays are changing/being sorted together when only one array is called to be changed/sorted
I have two arrays in my state, one is randomly generated and I want the other to be the sorted version of the random array.我的 state 中有两个 arrays,一个是随机生成的,我希望另一个是随机数组的排序版本。 Every time I call my sort function on my second array they always both change?
每次我在第二个数组上调用我的排序 function 时,它们总是都会改变? Does anyone know why this is.
有人知道为什么吗。 I'm pulling my hair out over this...
我正在为此拔头发...
constructor(props) {
super(props);
this.state = {
array: Array.from({ length: 10 }, () => Math.floor(Math.random() * 100)),
sortedArray: [],
};
this.generateArray = this.generateArray.bind(this);
};
render() {
return (
<div>
<button onClick={this.generateArray}>Generate Array</button>
</div>
);
}
generateArray(e) {
let a = this.state.array;
this.setState({ sortedArray: a.sort() });
}
When I call this function in my render method, both the state.array and state.sortedArray change to be sorted, how do I only sort one?当我在我的渲染方法中调用这个 function 时,state.array 和 state.sortedArray 都更改为排序,我如何只排序一个?
The Array.prototype.sort()
method in JavaScript sorts the array in-place; JavaScript 中的
Array.prototype.sort()
方法对数组进行就地排序; in other words, it changes the original array.换句话说,它改变了原始数组。 Putting a
slice()
in front of sort()
to make a shallow copy of the array will fix the problem: a.slice().sort()
将
slice()
放在sort()
前面以制作数组的浅表副本将解决问题: a.slice().sort()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.