Some practical experience of life cycle after using React+ANTD project

1.  constructor()
constructor(props){
   super(props)
  this.state=({
   })    
}
 

Be sure to write super  first to receive the value from the parent component

How to pass values ​​from parent component to child component

<ChildComponent  nextValue={xxx.xxx} nextValue2={xxx.xxx}/>

Just write the attribute name equal to the attribute value directly in the component, and pass as many as you want.

To get the value from the parent component in the child component ChildComponent only needs to use

this.props.nextValue

You can get the value from the parent component

This leads to a question, how does the child component pass values ​​to the parent component

First, you need to define a method (agechange) in the parent component, and then pass the method to the child component,

class App extends Component {
  agechange=(age)=>{
    alert(age)
  }
  
  render() {
    
    return (
      <div className="App">
        <Child agechange={ this .agechange}/> //Pass the method to the child component
      </div>
    )
  }
}

Calling this method in the child component will pass the value that needs to be passed to the parent component to the parent component through this method,

class Child extends Component {
    constructor(props){
        super(props)
        this.state=({
            age:0
        })
    }
    handleChange=()=>{
        this.setState({
            age:this.state.age+3
        })
        this .props.agechange( this .state.age) // Pass the age value of the child component to the parent component 
    }
    render(){
        return(
            <div>
                <button onClick={this.handleChange.bind(this)}>点击增加age</button>
            </div>
        )
    }
}

2.componentWillMount

   I just want to say one thing about the componentWillMount method. It is called after the constructor and before the render . The code in this method calls the setState method without triggering re-rendering.

3.componentDidMount

 

Generally, the data obtained from the background (server) will be related to the data loading to be used on the component, so it is used in the componentDidMount method.

 

4.componentWillReceiveProps

When the props passed by the parent component to the child component changes, the child component can receive it through the componentWillReceiveProps method, and the component can be re-rendered by setState. 
When the value obtained by the parent component asynchronously through ajax needs to be passed to the child component, the child component can use componentWillReceiveProps(nextProps(nextProps) )





Regarding setState(), it is not synchronous, nor can it be said to be asynchronous, so do not use the value in state directly after setState, it is easy to make mistakes.





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325990991&siteId=291194637