W
W
Weij33t2020-01-03 09:15:30
React
Weij33t, 2020-01-03 09:15:30

Why is the component not being rendered after changing the state?

There was a problem that after changing the state (debugging via console.log), the component does not rerender.
The component itself and its children depend on the state:

<div className="main-board">
            {this.state.cols.map((col, index) => {
              return (
                <Column
                  key={index}
                  id={index}
                  name={col.name}
                  colId={index}
                  col={this.state.cols[index]}
                  cards={this.state.cols[index].cards}
                  addCard={this.insertNewCard}
                  deleteCard={this.deleteHandler}
                />
              )
            })}


On clicking the button from the child component, the method from the parent is called:
insertNewCard = (id) => {
    this.setState((prevState) => {
      prevState.cols[id].cards = [
        ...prevState.cols[id].cards,
        {
          id: this.getNewId(),
          date: '11.11.1234',
          grade: '10',
          name: 'Созданный',
        },
      ]
      return {
        cols: prevState.cols,
      }
    })
  }


As already mentioned, the state is updated, the render methods are called both in the child and in the parent, the changed state is displayed in the console, but no re-rendering occurs.

Life cycles are not used, another similar method also changes the method, but redrawing occurs (adding a column)

insertNewCol() {
    console.log('insertNewCol')
    this.setState((prevState) => {
      return {
        cols: [
          ...this.state.cols,
          {
            name: 'Созданная колонка',
            cards: [
              {
                id: this.getNewId(),
                date: '00.00.9999',
                grade: '1',
                name: 'Новая карточка',
              },
            ],
          },
        ],
      }
    })
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2020-01-03
@alexey-m-ukolov

cols: prevState.cols,

Why are you mutating the previous state object?
You always return a reference to the same object, so React does not understand that it has changed, because it does not look inside the object.
this.setState((prevState) => {
  return {
    cols: prevState.map((col, index) => {
      if (index !== id) {
        return col;
      }

      return {
        ...col,
        cards: [
           ...col.cards,
           {/*new card fields*/}
        ]
      }
    }
  }
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question