React function components use State and lifecycle methods (componentDidMount, etc.)
![React function components use State and lifecycle methods (componentDidMount, etc.) React function components use State and lifecycle methods (componentDidMount, etc.)](http://up-free-imgs.azimiao.com/wp-content/uploads/2020/05/react.png)
What is React Hook
useState
If an object is used as a state, its value will be directly replaced when useState is updated, instead of merging the updated fields into the object as setState does. It is recommended to divide the State object into multiple State variables.
function AComponent(){ const [allNumber,setAllNumber] = React.useState(1); return( <div> {allNumber} <button onClick={() => setAllNumber(allNumber + 1)}>test</button> </div> ) }
class AComponent extends React.Component{ Constructor (props) super(props);// Meow this.state = {//chu AllNumber: 1//mo blog };// www.azimiao.com } render(){ return( <div> {this.state.allNumber} <button onClick={() => this.setState({allNumber: this.state.allNumber + 1})}> test </button> </div> ); } }
useEffect
Execute after each update
function AComponent(props){ React.useEffect(()=>{ Console.log ("The pair will be executed after each update"); }); }
Execute after a status change
function AComponent(props){ React.useEffect(()=>{ Console.log ("After one execution, the allNumber value will change and be executed again"); },[allNumber]); }
ComponentDidMount and componentWillUnmount
function AComponent(){ React.useEffect(()=>{ console.log("componentDidMount"); // Return function cleanup() {console. log ("The component is uninstalled componentWillUnmount")}; },[]); }