Will setState inside the WillReceiveProps component run before rendering?

Valid documents mention that calls setStateare queued, and this does not happen immediately. Does any guarantee that setStatethe queue componentWillReceivePropswill be executed until the next component rendering? Are these scenarios more likely than others?

  • props change> componentWillReceiveProps called> setState enqueued> setState run> render (which includes the new state)

  • props change> componentWillReceiveProps called> setState enqueued> render> setState run> re-rendered

Or are both scenarios equally likely? React value makes no guarantee when setState will work relative to component life cycle methods?

Here is the ES2015 code snippet of my example:

import React from 'react';

class Widget extends React.Component {

  componentWillReceiveProps() {
    this.setState({foo: 'bar'});
  }

  render() {
    return <div>
      <a onClick={(e) => {
        e.preventDefault();
        this.props.triggerExternalPropsChange();
      }}>
        Click me to trigger new props
      </a>
    </div>;
  }
}

Where triggerExternalPropsChangetransfers the new supports to the component Widget.

+4
source share
3 answers

The only reason componentWillReceivePropsis to give the component an opportunity setState. So yes, any state that you set synchronously in it will be processed along with the new details. In this case, there will not be two renderings, only one.

+15
source

, . , , , , . , shouldComponentUpdate , .

0

This is 1.

The call to setState () in the component WillReceiveProps () is an exception in the sense of performing a state update before the component is displayed, so you will get both props and state changes applied in the same render.

0
source

Source: https://habr.com/ru/post/1680312/


All Articles