henhen
henhen

Reputation: 1205

state array keeps reordering

I have an array of objects in my React Class component, and when I click on the class private methods, the order of the array keeps shuffling for some reason. What I am trying to do is, re-order the array by first assigning it to a variable and then setting state to another array that is just set as empty. However, even before I begin splicing the array, the console log is showing that the original array keep reordering.

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

Upvotes: 0

Views: 215

Answers (1)

nbkhope
nbkhope

Reputation: 7474

You are calling splice() on a state property. That method mutates the caller. You should never mutate the state directly. You should always make a copy of the state property and work with that.

If you want to reorder the array of objects in the state somehow, try using the slice method to get parts of the array you want. Then, you can combine those using concat. For example, to bring the first element of the list to the end of the list:

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

Example output (I copied from a Chrome web console):

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

Upvotes: 1

Related Questions