Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 状态数组保持重新排序_Javascript_Arrays_Reactjs - Fatal编程技术网

Javascript 状态数组保持重新排序

Javascript 状态数组保持重新排序,javascript,arrays,reactjs,Javascript,Arrays,Reactjs,我的React类组件中有一个对象数组,当我单击类私有方法时,由于某种原因,数组的顺序一直在混乱。我想做的是,首先将数组赋给一个变量,然后将状态设置为另一个刚设置为空的数组,从而对数组重新排序。然而,甚至在我开始拼接阵列之前,控制台日志显示原始阵列仍在重新排序 constructor (props) { super(props); this.state = { content:[ { one: 'ONE'

我的React类组件中有一个对象数组,当我单击类私有方法时,由于某种原因,数组的顺序一直在混乱。我想做的是,首先将数组赋给一个变量,然后将状态设置为另一个刚设置为空的数组,从而对数组重新排序。然而,甚至在我开始拼接阵列之前,控制台日志显示原始阵列仍在重新排序

constructor (props) {
    super(props);
    this.state = {
        content:[
            {
              one: 'ONE'
            },
            {
              two: 'TWO'
            },
            {
              three: 'THREE'
            }
        ],
        contentMix: null,  //The array I am going to assign the spliced array to.
     }

  someMethod () { //assume it is binded in constructor.
       /*When I click on element in render that calls this method, I console log 
      `this.state.content, and it is showing the array is out of order than what I have declared in the contructor, even though I 
       have not started splicing the arr or not even touching or changing the state 
       of this array.*/

       let arr = this.state.content
       let elementOne = this.state.content[0];
       let elementTwo = this.state.content[1];
       arr.splice(0, 2, elementTwo, elementOne)

       this.setState({ contentMix: arr})
  }

您正在对状态属性调用
splice()
。该方法对调用方进行变异。你不应该直接改变状态。您应该始终复制state属性并使用它

如果要以某种方式对状态中的对象数组重新排序,请尝试使用
slice
方法获取所需数组的部分。然后,您可以使用
concat
组合这些。例如,要将列表的第一个元素置于列表的末尾,请执行以下操作:

const firstItem = this.state.content.slice(0, 1); // this generates a single-element array
const listWithoutFirst = this.state.content.slice(1);
this.setState({ content: listWithoutFirst.concat(firstItem) });
输出示例(我从Chrome web控制台复制):


您正在对状态属性调用splice()。该方法对调用方进行变异。你不应该直接改变状态。您应该始终复制state属性并使用它。这不是我正在使用的吗?让arr=this.state.content?在JS中,对对象的赋值给出的是引用,而不是副本
arr
是对
this.state.content
的引用,您正在修改原始数组。而是像这样创建新数组
let arr=[…this.state.content]
No,它不会生成副本。它只是将状态属性的引用分配给名为
arr
的变量。如果要对状态中的对象数组重新排序,应首先复制该数组并对其重新排序。我只需要使用slice来获取除第一个元素之外的所有元素;然后使用切片的第一个元素将其合并,以获得位于(新)数组末尾的第一个元素。
this.state = { content: ['a', 'b', 'c'] };
// ...
listWithoutFirst.concat(firstItem) // => ["b", "c", "a"]