Out of curiosity, I just wanna know what will happen if I use setState()
function in constructor of a Class in React Native or ReactJS? Such as:
constructor(props) { super(props); this.setState({title: 'new title'}); }
what's the lifecycle of React gonna happen?
I haven't read the code inside React. I am afraid it will some any damage when I write it that way.
setState" causes React to re-render your application and update the DOM. you can also track of prevstate in setState If you use setState in constructor you would get error like this:Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component.
Use the setState() method everywhere else; doing so accepts an object that eventually merges into the component's existing state. For example, the following does not rerender a component: // Wrong this.state.name = 'Obaseki Nosa'; Instead, use setState() .
The first thing React will do when setState is called is merged the object you passed into setState into the current state of the component. This will kick off a process called reconciliation. The end goal of reconciliation is to, in the most efficient way possible, update the UI based on this new state.
setState() is used to change the name in componentWillMount() and componentDidMount() and the final name is reflected on the screen. An important thing to note here isthat as stated before, componentDidMount() occurs only once to give a render a second pass.
What setState
essentially does is to run a bunch of logic you probably don't need in the constructor.
When you go state = {foo : "bar"}
you simply assign something to the javascript object state
, like you would any other object. (That's all state
is by the way, just a regular object local to every component).
When you use setState()
, then apart from assigning to the object state
react also rerenders the component and all its children. Which you don't need in the constructor, since the component hasn't been rendered anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With