Home > Blockchain >  Splice an array in React keeps rerendering
Splice an array in React keeps rerendering

Time:12-21

In the update(changeProps) function, I have something like this:

 update(changedProps) {
      if (this.person) {
        this.__arr = ['hi', 'hi', 'hi'];
      } else {
        this.__arr = ['bye', 'bye', 'bye', 'bye'];
      }

    if (this.__hello) {
      this.__arr.splice(1, 0, 'hello');
    }

    super.update(changedProps);
  }

Say this.person is true, when I click elsewhere and the page rerenders, it becomes

this.__arr = ['hi', 'hello', 'hi', 'hi']

Then when it rerenders again: this.__arr = ['hi', 'hello','hello', 'hi', 'hi']

It keeps adding to the array after each rerender. Same for if this.person is not true. How do I make it so it only adds it once?

If I did something like this: this.__arr = [...this.__arr, 'hello'], it can add it to the end, but I want to add an element to index 1

CodePudding user response:

Two things:

  1. Don't mutate:
    if (this.__hello) {
      this.__arr = [...this.__arr].splice(1, 0, 'hello');
    }
  1. Do you want to do this every time the component updates, or just once?
    if (this.__hello && this.__arr[1] !== 'hello') {
      this.__arr = [...this.__arr].splice(1, 0, 'hello');
    }
  • Related