The solution for state fails to reset when using setState in componentDidUpdate()

The problem

I tried to update state in componentDidUpdate() of a child component.
But the state fails to reset.

# In the child component
componentDidUpdate(prevProps) {
  if (prevProps.listNum !== this.state.listNum) {
    this.setState({listNum: prevProps.listNum});
  }
}

The solution

I fixed to manage state in a parent component.
The parent’s state is given to the child component as props.

Why I do the solution

Using componentDidUpdate() for updating state is an anti-pattern of React.js.

Check the public document.

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です