Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

What will happen if I use setState() function in constructor of a Class in ReactJS or React Native?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...