current position:Home>React -- 14: life cycle old version
React -- 14: life cycle old version
2021-08-27 00:14:33 【CSDN to dig the foot of the wall】
This is my participation 8 The fourth of the yuegengwen challenge 20 God , Check out the activity details :8 Yuegengwen challenge
First , Let's use an example to lead to : Counter
1. Mount stage
- constructor Constructors
- componentWillMount About to mount
- componentDidMount The mount is finished
- render Rendering
We are in the hook of each life cycle A print , Look at their execution order .
class Count extends React.Component {
constructor(props) {
console.log("count-constructor")
super(props)
// Initialization status
this.state = {
count: 0
}
}
// About to mount
componentWillMount() {
console.log("componentWillMount")
}
// The mount is finished
componentDidMount(){
console.log("componentDidMount")
}
// +1 Button callback
add = () => {
// Get the original state
const { count } = this.state
// Update status
this.setState({ count: count + 1 })
}
render() {
console.log("count-render")
return (
<div> <h1> The current sum is {this.state.count}</h1> <button onClick={this.add}> Am I +1</button> </div>
)
}
}
Copy code
The order of execution is as follows : You can see the warning in the figure ,componentWillMount Has been abandoned . But you can still use .
2. to update
There are three ways to update :
2.1 setState
In the previous article , We said setState Update meeting call render. But in fact, I have experienced shouldComponentUpdate( No, the component should be updated )、componentWillUpdate Two processes .
- shouldComponentUpdate
We haven't written before shouldComponentUpdate This hook function ? Why is it updated ? This hook has a return value , The default return value is true, Only his return value is true, To execute down . When we write this hook function ourselves , And the return value is false When . It won't go down .️ There must be a return value true/false.
shouldComponentUpdate(){
console.log("shouldComponentUpdate")
return true
}
Copy code
- componentWillUpdate The hook that the component will update
- componentDidUpdate Hook after component update
2.2 forceUpdate
Force update , That is, I don't want to use setState Also update the status . And setState The difference is : Not pass shouldComponentUpdate.
We added a new button , Click the button to start force Callback function . Use... In callback functions forceUpdate.forceUpdate and setState Both need this.
force =()=>{
this.forceUpdate()
}
render() {
console.log("count-render")
return (
<div> <h1> The current sum is {this.state.count}</h1> <button onClick={this.add}> Am I +1</button> <button onClick={this.death}> The destruction </button> <button onClick={this.force}> Force update </button> </div>
)
}
Copy code
Click force update , We found that the following three hooks were executed .
The complete code of the above two methods
class Count extends React.Component {
constructor(props) {
console.log("count-constructor")
super(props)
// Initialization status
this.state = {
count: 0
}
}
// About to mount
componentWillMount() {
console.log("componentWillMount")
}
// The mount is finished
componentDidMount() {
console.log("componentDidMount")
}
// +1 Button callback
add = () => {
// Get the original state
const { count } = this.state
// Update status
this.setState({ count: count + 1 })
}
// The callback to unload the component
death = () => {
ReactDOM.unmountComponentAtNode(document.getElementById('root'))
}
// The component is about to unload and call
componentWillUnmount() {
console.log("componentWillUnmount")
}
// Controls the of component updates “ valve ”
shouldComponentUpdate() {
console.log("shouldComponentUpdate")
return true
}
// The hook that the component will update
componentWillUpdate() {
console.log("componentWillUpdate")
}
// Hook after component update
componentDidUpdate() {
console.log("componentDidUpdate")
}
force = () => {
this.forceUpdate()
}
render() {
console.log("count-render")
return (
<div> <h1> The current sum is {this.state.count}</h1> <button onClick={this.add}> Am I +1</button> <button onClick={this.death}> The destruction </button> <button onClick={this.force}> Force update </button> </div>
)
}
}
Copy code
2.3 Parent component render
First, let's write two new components , Let them form a father son relationship .
class A extends React.Component {
render() {
return (
<div> A <B /> </div>
)
}
}
class B extends React.Component {
render() {
return (
<div>B</div>
)
}
}
ReactDOM.render(<A />, document.getElementById('root'))
Copy code
stay A Components ( Parent component ) Of state Define a variable in carName, And in A Add buttons and changes to components carName Callback function for . most important of all , I don't want to A Show the car name in the component , I want to put B Component .
class A extends React.Component {
state ={carName:"BM"}
changeCar = ()=>{
this.setState({carName:"AD"})
}
render() {
return (
<div> I am a A Components <button onClick={this.changeCar}> Change </button> <B carName={this.state.carName}/> </div>
)
}
}
Copy code
B Components ( Child components ), Just through props Receive parent component A, From the value of the
class B extends React.Component {
render() {
return (
<div> I am a B Components , What was received was {this.props.carName}</div>
)
}
}
Copy code
Then it leads to the hook componentWillReceiveProps ( The component will receive props)
class B extends React.Component {
componentWillReceiveProps(){
console.log("componentWillReceiveProps")
}
render() {
return (
<div> I am a B Components , What was received was {this.props.carName}</div>
)
}
}
Copy code
The second reception props
We just entered the page , The parent component has passed... To the child component props. But this hook does not perform . When we click the button to update , Just executed this hook .
3. The destruction
Click the button to destroy the component , We are componentWillUnmount Print in hook function . When the button is clicked , Execute this print .
death =()=>{
ReactDOM.unmountComponentAtNode(document.getElementById('root'))
}
// The hook that the component will unload
componentWillUnmount(){
console.log("componentWillUnmount")
}
render() {
console.log("count-render")
return (
<div> <h1> The current sum is {this.state.count}</h1> <button onClick={this.add}> Am I +1</button> <button onClick={this.death}> The destruction </button> </div>
)
}
Copy code
copyright notice
author[CSDN to dig the foot of the wall],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827001429611W.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- JQuery operation select (value, setting, selected)
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- [vue3] encapsulate custom global plug-ins
- Error using swiper plug-in in Vue
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
guess what you like
-
Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
-
He was cheated by Wang Xiaofei and Li Chengxuan successively. Is an Yixuan a blessed daughter and not a blessed home?
-
Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
-
Pink is Wangyuan online! Back to the peak! The new hairstyle is creamy and sassy
-
Front end interview daily 3 + 1 - day 858
-
Spring Webflux tutorial: how to build reactive web applications
-
[golang] walk into go language lesson 24 TCP high-level operation
-
August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
Random recommended
- Anti Mafia storm: He Yun's helpless son, Sun Xing, is destined to be caught by his dry son
- Introduction to flex flexible layout in CSS -- learning notes
- CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
- Today, let's talk about the arrow function of ES6
- Some thoughts on small program development
- Talk about mobile terminal adaptation
- Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
- JS function scope, closure, let, const
- Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
- Unveil the mystery of ascension
- Asynchronous solution async await
- Analysis and expansion of Vue infinite scroll source code
- Compression webpack plugin first screen loading optimization
- Specific usage of vue3 video play plug-in
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- [25] typescript
- CSS transform Complete Guide (Second Edition) flight.archives 007
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- Decorator pattern of JavaScript Design Pattern
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich