state数组保持重新排序

时间:2017-09-21 17:21:58

标签: javascript arrays reactjs

我的React Class组件中有一个对象数组,当我点击类私有方法时,由于某种原因,数组的顺序保持混乱。我想要做的是,通过首先将数组分配给变量然后将状态设置为另一个刚刚设置为空的数组来重新排序数组。但是,即使在我开始拼接数组之前,控制台日志也会显示原始数组不断重新排序。

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})
  }

1 个答案:

答案 0 :(得分:1)

您正在州政府财产上调用splice()。该方法改变来电者。你永远不应该直接改变状态。您应该始终对状态属性进行复制并使用该属性。

如果要以某种方式重新排序状态中的对象数组,请尝试使用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网络控制台复制):

this.state = { content: ['a', 'b', 'c'] };
// ...
listWithoutFirst.concat(firstItem) // => ["b", "c", "a"]