join us!
Mountain" , to provide front-end developers with technical information and a series of basic articles. For a better user experience, please move to our official website novices (160d9494f81435 https://xhs-rookies.com/ ) to learn and get the latest articles in time.
"Code tailor" , if you are interested in our article or want to make some suggestions, follow Mountain" public account, contact us, you can also watch it on WeChat Our article. Every suggestion or approval is a great encouragement to us!
Preface
In this section, we will introduce React
, and the life cycle related life cycle functions.
Note: The life cycle introduced in this article is React 17.0.1, and there may be changes during the reader period. The final life cycle and other methods and processes should be based on the official website, react official website
This article will introduce you to the following:
- Understanding the life cycle
- Life cycle analysis
- Common life cycle functions
- Unusual life cycle
Understanding the life cycle
Many things have the entire process from creation to destruction. This process is called life cycle ;
React
component also has its own life cycle. Understanding the life cycle of the component allows us to complete the functions we want in the most suitable place;
After the components go through different life cycles, different life cycle functions will be triggered, let us write logic in the most suitable place.
E.g:
There is a component that needs to call the network to request data when it is generated, so the network should be componentDidMount()
method.
Note: we talk React
life cycle life cycle, mainly about the class, because there is no functional component life cycle functions;
Life cycle analysis
Each class component contains "life cycle methods". You can override these methods to execute these methods at a specific stage in the running process. Let's learn about these life cycle functions. The following is the official life cycle Atlas:
mounted:
- When we mount a component, we will first execute the
constructor
construction method to create the component; - Then it will call
getDerivedStateFromProps
, it should return an object to updatestate
, if it returnsnull
be updated. - Then call the
render
function to get theDOM
structure (jsx
) to be rendered, and start renderingDOM
; - When the component is successfully mounted (
DOM
rendering is completed), thecomponentDidMount
life cycle function will be executed;
updated:
- When we modify
props
, or callsetState
modify the internal state, or directly callforceUpdate
, the 060d9494f819ee function will be calledrender
perform the update operation; - The update is triggered when the
props
orstate
getDerivedStateFromProps
will be called at this time, it should return an object to updatestate
, if it returnsnull
be updated. shouldComponentUpdate
is called, and based on the return value of this function, it is judged whether the output of the React component is affected by the current state or props changes.render
function will be called immediately, and thengetSnapshotBeforeUpdate
will be called for the update operation- When the update is completed, the life cycle function of
componentDidUpdate
uninstalled:
- When our components are no longer used, they will be removed from
DOM
(uninstall); - At this time, the life cycle function of
componentWillUnmount
Common life cycle functions
render
render()
render()
method is the only method that must be implemented in the class
When render
is called, it will check this.props
and this.state
and return one of the following types:
- React element . Usually created
JSX
- array or fragments .
render
method can return multiple elements. - Portals . You can render child nodes to different
DOM
subtrees. - string or numeric type . They will be rendered as text nodes
DOM
- Boolean type or
null
. Nothing is rendered.
render()
function should be a pure function, which means that without modifying the component state
, it will return the same result every time it is called, and it will not directly interact with the browser.
If you need to interact with the browser, please componentDidMount()
or other life cycle methods. Keeping render()
as a pure function can make the component easier to think about.
Note: ifshouldComponentUpdate()
returnfalse
, is not calledrender()
.
constructor
constructor(props)
state
is not initialized or method binding is not performed, there is no need to implement a constructor React
Usually only two things are done in constructor
this.state
assigning a value tostate
;- For the event binding instance (
this
);
constructor(props) {
super(props);
// 不要在这里调用 this.setState()
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}
You can only assign a value this.state
directly in the constructor. If you need to assign values in other methods, you should use this.setState()
instead.
Note: avoidprops
the value ofstate
to 060d9494f832d8! This is a common mistake
componentDidMount
componentDidMount()
componentDidMount()
will be called immediately after the component is mounted (inserted into the DOM tree).
Where is the operation usually performed in componentDidMount
- Operations that depend on
DOM
can be performed here; - The best place to send network requests here; (official suggestion)
- You can add some subscriptions here (subscriptions will be
componentWillUnmount
);
componentDidUpdate
componentDidUpdate(prevProps, prevState, snapshot)
componentDidUpdate()
will be called immediately after the update, and this method will not be executed for the first rendering.
- After the component is updated, you can operate
DOM
here; props
before and after the update, you can also choose to make a network request here; (for example, whenprops
no change in 060d9494f8358f, the network request will not be executed).
componentDidUpdate(prevProps) {
// 典型用法(不要忘记比较 props):
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}
You can also componentDidUpdate()
in direct call setState()
, but please note it must be wrapped in a conditional statement in , processed as described above as an example, otherwise it will lead to an endless loop.
Note: ifshouldComponentUpdate()
return valuefalse
, is not calledcomponentDidUpdate()
.
componentWillUnmount
componentWillUnmount()
componentWillUnmount()
will be called directly before the component is unloaded and destroyed.
- Perform necessary cleanup operations in this method, such as clearing
timer
, canceling network requests, or clearing subscriptions createdcomponentDidMount()
componentWillUnmount()
in should not callsetState()
because the component will never be re-rendered. After the component instance is uninstalled, it will never be mounted again.
code verifies the above-mentioned commonly used life cycle functions:
import React, { Component } from 'react'
class HYTestCpn extends Component {
render() {
return <h2>HYTestCpn</h2>
}
componentWillUnmount() {
console.log('HYTestCpn componentWillUnmount')
}
}
export default class App extends Component {
constructor(props) {
super(props)
this.state = {
counter: 0,
}
console.log('调用constructor方法')
}
render() {
console.log('调用render方法')
return (
<div>
<h2>当前计数: {this.state.counter}</h2>
{this.state.counter <= 5 && <HYTestCpn />}
<button onClick={(e) => this.increment()}>+1</button>
</div>
)
}
increment() {
this.setState({
counter: this.state.counter + 1,
})
}
componentDidMount() {
console.log('调用componentDidMount方法')
}
componentDidUpdate() {
console.log('调用componentDidUpdate方法')
}
componentWillUnmount() {
console.log('调用componentWillUnmount方法')
}
}
Unusual life cycle
In addition to the commonly used life cycle functions described above, there are some less commonly used life cycle functions:
shouldComponentUpdate
shouldComponentUpdate(nextProps, nextState)
When props
or state
changes, shouldComponentUpdate()
will be called before rendering is executed. The default return value is true
. This method will not be called when forceUpdate()
for the first time.
- The
shouldComponentUpdate()
return value, determinedReact
component output is affected by the currentstate
orprops
affected by the change. - The default behavior is that
state
will re-render every time the component changes. In most cases, you should follow the default behavior. - This method only exists as a way to optimize the performance of . Do not attempt to rely on this method to "prevent" rendering, as this may produce
bug
.
We should first consider using the built-in PureComponent
component instead of manual writing. PureComponent
will props
and state
, and reduce the possibility of skipping necessary updates.
If you need to write manually, you can compare this.props
with nextProps
and this.state
with nextState
, and return false
to inform React
that the update can be skipped. Please note that returning to false
will not prevent the child component from re-rendering when the state changes.
getDerivedStateFromProps
static getDerivedStateFromProps(props, state)
getDerivedStateFromProps
will be called render
method, and will be called during the initial mount and subsequent updates.
- It should return an object to update
state
, if it returnsnull
be updated. getDerivedStateFromProps
there is only one purpose: to make components in props change updatestate
, namelystate
value at any time depending onprops
.- This method does not have access to the component instance.
Note: will trigger this method before each rendering regardless of the reason.
getSnapshotBeforeUpdate
getSnapshotBeforeUpdate(prevProps, prevState)
DOM
React
update 060d9494f85136, you can get DOM
update (such as scroll position);
- Any return value of this life cycle will be passed to
componentDidUpdate()
as a parameter. - This usage is not common, but it may appear in
UI
processing, such as chat threads that need to handle the scroll position in a special way. - It should return
snapshot
value (ornull
).
In addition, React
also provides some expired life cycle functions, these functions are no longer recommended.
For more detailed life cycle related content, please refer to React official website
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。