These methods are called when a component is initialized, and only when the instance is created.
If created with createReactClass, there are also life cycle functions like getInitialState, which are rarely used and will not be covered here.
Static defaultProps{} (getDefaultProps()) defines the defaultProps, which is merged with the props passed from the parent component. The parent component has a higher priority, which is equivalent to {… DefaultProps, props}.
Static propTypes{} (getInitialState()) defines the props data type, which can help us determine its validity and reduce many unnecessary errors in development.
Constructor () is called once before the load phase to initialize state.
constructor(props){
super(props) }
Super (props) is used to call the build method of the parent class.
Mounting (Loading stage) componentWillMount() In the new version, UNSAFE_componentWillMount().
It is called only when the component is loaded, only once throughout the lifecycle, and not later when the component is updated, at which point you can change state.
Render () React is the most important lifecycle function, which creates the virtual DOM and performs the diff algorithm, as well as updating the DOM tree. You should not change the state of the component or interact with the browser here.
Note: This function cannot be missing. If you do not create the virtual DOM, you can return null.
ComponentDidMount () is called immediately after the component is loaded, only once for the entire life cycle, to retrieve the updated DOM, where network requests can be made, etc.
Updating phase (update) componentWillReceiveProps () in the new version for UNSAFE_componentWillReceiveProps ().
This function is called first if any new props are passed after the component is loaded. You can change state by calling setState() here.
componentWillReceiveProps(nextProps)
ShouldComponentUpdate () React is an important performance optimization point. When a component receives new props or state, return true to say it needs to update the DOM, and return false to block the update.
shouldComponentUpdate(nextProps, nextState)
ComponentWillUpdate () is UNSAFE_componentWillUpdate().
It is not called when the component is loaded, only when the component needs to be updated (shouldComponentUpdate returns true).
componentWillUpdate(nextProps, nextState)
Note: You cannot change state in this method by calling setState().
Otherwise updating will be retriggered
Render () componentDidUpdate() is called immediately after component updates are complete, can make network requests etc.
componentDidUpdate(prevProps, prevState)
Unmouting componentWillUnmount() is called before the component is unmounted and destroyed, and it is here to handle any necessary cleanup, such as undoing timers, canceling network requests that have been initiated, Cleans up DOM elements created in the componentDidMount function.
componentWillUnmount()
ComponentDidCatch () Error bound Catch, a new lifecycle function added in v16.0 to catch JavaScript errors that occur anywhere in the subcomponent tree. An error bound cannot catch its own internal errors.
componentDidCatch(error, info)
First of all, three life cycles have been removed from the new release and will be deprecated:
componentWillReceiveProps componentWillMount componentWillUpdate getDerivedStateFromProps()
GetDerivedStateFromProps is a static function, so the function body cannot access this. In a pure function, the output depends entirely on the input.
static getDerivedStateFromProps(nextProps, prevState) {
// Calculate the expected state changes based on nextProps and prevState, and the return is sent to setStateCopy the code
} getDerivedStateFromProps is called whenever the parent component triggers the rendering process of the current component, so we have an opportunity to adjust the new props state based on the new props and the previous state. If implemented in three deprecated lifecycle functions, it is pure. If there are no side effects, you can basically just move to getDerivedStateFromProps;
Note: getDerivedStateFromProps is called whether Mounting or Updating or whatever caused the Updating.
getSnapshotBeforeUpdate()
This function is executed after render, when the DOM element has not been updated, giving an opportunity to retrieve DOM information and calculate a snapshot, which is passed in as the third parameter to componentDidUpdate.
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log('#enter getSnapshotBeforeUpdate');
return 'foo';
Copy the code
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('#enter componentDidUpdate snapshot = ', snapshot);
Copy the code
} getSnapshotBeforeUpdate returns snapshot, then DOM changes, then snapshot is passed to componentDidUpdate.
Summary: Replacing the purged lifecycle functions with a static function getDerivedStateFromProps forces developers to perform only side-effect operations before Render, and the only operations they can do are to determine the new state according to props and state. This is to further impose constraints and prevent developers from messing around
1. Willmount or didmount?
ComponentWillMount is implemented before render, and the result can be obtained as soon as possible.
However, keep in mind that launching AJAX in componentWillMount, no matter how fast you get the result, can’t keep up with the first render,
And componentWillMount is also called for rendering on the server side (of course, maybe this is the intended result),
IO operations like this are better placed in componentDidMount. After Fiber enabled Async Render, there’s no reason to do AJAX in componentWillMount,
Because componentWillMount can be called multiple times, you don’t want to call AJAX multiple times for nothing.
React developers have been thinking about this for a long time, which is why they created a new life cycle. Since they don’t want to put it in such a bad life cycle, they might as well just make it impossible for them.
2. When to use forceUpdate?
ForceUpdate is rerender. Some variables are not in state, but you want to refresh render when the variable is updated;
Or a variable in state is so deep that it doesn’t automatically trigger render when updated.
In these cases, forceUpdate can be called manually to trigger Render automatically. Therefore, it is recommended to use IMmutable to manipulate state, and flux architectures such as Redux to manage state.
How does a parent component’s state change affect the child component’s life cycle?
The shouldComponentUpdate function takes nextProps and nextState as arguments.
You can use either the props or the state to determine if an update is needed. For example, determine whether this.state.count equals nextstate. count.
React componentWillUpdate () {setState ();
If setState is called in shouldComponentUpdate and componentWillUpdate,
At this point this _pendingStateQueue! = null, the performUpdateIfNecessary method calls the updateComponent method to update the component.
But the updateComponent method calls shouldComponentUpdate and componentWillUpdate,
This creates a loop that causes the browser to crash when it fills up memory.
Do functional components have a life cycle? Why is that?
Because functional components do not inherit from React.component. because lifecycle functions are implemented by methods of the React.componentclass
So if you don’t inherit from this class, you can’t use life cycle functions
6. What’s the difference between PureComponent and Component?
PureComponent advantage:
ShouldComponentUpdate does not require developers to implement it themselves to make simple judgments to improve performance.Copy the code
PureComponent faults:
The React.PureComponent implements shouldComponentUpate() by using a shallow contrast between props and state.Copy the code
In PureComponent, if you include complex data structures, you can make false negative judgments due to deep data inconsistencies and the interface will not be updated.
ShouldComponentUpdate is handled by the PureComponent itself, not by the user.
So if we overwrite the lifecycle callback in the PureComponent, React will tell us it’s wrong. Tells us that we are not allowed to override the method.
7. Why does PureComponent’s complex data structure lead to false negative judgments due to deep data inconsistencies?
Objects in JavaScript are generally Mutable because, using reference assignment, new objects simply refer to the original object,
Changing the new object affects the original object.
Such as
foo={a: 1};
bar=foo;
Bar. A =2 and you’ll notice that foo.a is also changed to 2.
To solve this problem, it is common practice to use shallowCopy or deepCopy to avoid being modified, but this results in wasted CPU and memory.
The reason is that js uses reference assignment, the new object simply refers to the original object, and changing the new object affects the original object,
But the address of the object is still the same, using === equality.
In PureComponent, prop is judged equal without triggering Render ().
The easiest way to avoid such problems is to avoid using properties or states whose values might mutate and instead use a copy that returns a new variable
8. Is setstate in React synchronous or asynchronous? Rax?
Event handlers controlled by React, as well as life cycle function calls to setState, do not update state synchronously.
Calls to setState in events outside of React control are updated synchronously. Such as native JS bound events, setTimeout/setInterval, etc.
Most development uses React encapsulated events, such as onChange, onClick, onTouchMove, etc. SetState in these event handlers is handled asynchronously.
The setState of Rax is synchronous
9. How does React control asynchrony and synchronization?
In the React setState implementation, isBatchingUpdates are made according to a variable
Determine whether to update this.state directly or to queue it for delayed updates.
IsBatchingUpdates default to false, meaning setState will update this.state;
However, there is a function called batchedUpdates that changes isBatchingUpdates to true,
React calls this batchedUpdates function before calling the event handler to change isBatchingUpdates to true,
Such a React controlled event handler setState will not update this.state synchronously.
What are some uses of setState?
(1) Multiple setState calls will be combined:
In some handlers setState is called twice, but Render is executed only once.
React will place multiple this.setState changes in a queue for batch delay processing.
(2) Parameter is the setState usage of the function
So let’s say I want to do something after setState updates state,
And setState might be asynchronous, so how do I know when it’s done.
So setState provides functional usage
Receives two function arguments, the first calling to update state, and the second callback after the update.
Case:
handleClick() { this.setState({
Count: this.state.count + 1})} The above operations have potential pitfalls and should not rely on their values to calculate the next state.
handleClick() { this.setState({
count: this.state.count + 1 }) this.setState({
count: this.state.count + 1 }) this.setState({
Count: this.state.count + 1})} This.setState is set to the same value over and over again
handleClick() { const count = this.state.count
this.setState({
count: count + 1 }) this.setState({
count: count + 1 }) this.setState({
Count: count + 1})} count is a snapshot, so no matter how many times it is repeated, the result is incremented by 1.
The first function accepts the previous state as the first argument and the props at which the update was applied as the second argument.
increment(state, props) { return {
count: state.count + 1 } }
handleClick() { this.setState(this.increment) this.setState(this.increment) this.setState(this.increment) } In the case of multiple calls to the functional setState function, React ensures that each time increment is called, the state has been merged with the previous state changes.
That is, the first time you call this.setState(increment),
The count of the state parameter passed to increment is 10, the second call is 11, the third call is 12, and the result of the handleClick execution is this.state.count is 13.
Note that this.state is not changed when increment is called.
Still wait until the render function is re-executed (or after shouldComponentUpdate returns false)
Because render only executes once.