In the constructor, I declare state :

 data: this.shuffle(this.newMassiv(25)) 

In componentWillMount , componentDidMount and render I call console.log(this.state.data) .
As you can see, in the didmount array is reset. state.data does not change anywhere.

Why is state.data reset? Tried to set value in componentWillMount - the same.

  • one
    See the code for the text. - Roman C

1 answer 1

You need to know when this or that method will be called.

  • constructor - the constructor for the React component is called before it is mounted. A constructor is the right place to initialize a state. A constructor is also often used to bind event handlers to an instance of a class.

  • componentWillMount - called immediately before the component is mounted and rendered (in other words, by the render() ). It is not recommended to call the setState method inside this method; usually, a constructor is used to initialize the state. This method is considered unsafe. Inside it is not possible to look at or access the DOM elements.

  • render - the required method, the rendering of the component itself. The code of this method must be clean, which means that it does not change the state of the component. The method must return the same result for each call and does not interact directly with the browser.

  • componentDidMount - called immediately after the component is mounted. Typically used to download data through requests or a place to set up a subscription to events. If you need to do something with DOM elements, then it’s better here that it is called after drawing, which means after render . A call to setState in this method will cause additional rendering, but this will happen before the browser refreshes the screen. This ensures that even if render() is called twice in this case, the user will not see the intermediate state.

The sequence of calling methods is:

  1. constructor
  2. componentWillMount
  3. render
  4. componentDidMount

If you assign a value to state in constructor and that value is in the componentWillMount and render methods, but not in componentDidMount , then the state value is updated somewhere in the depths of your render . Perhaps you are passing your state to child elements and changing it there — that is also possible. Not seeing the full code - you can not give a specific answer. You need to carefully look at the code and find a place where the value changes. There is no way that state did not come before the componentDidMount method.