React function components use State and lifecycle methods (componentDidMount, etc.)

For a function component, there are no life cycle methods such as componentDidMount and componentDidUpdate in the class component, and there is no State, but these can be implemented through React Hook.

What is React Hook

Hook It is a special parameter. It is a new feature in React 16.8. It allows you to use State and other React features without writing a class.

useState

Use the State attribute in function components.

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> ) }

Equivalent to:

 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

Effect Hook is equivalent to componentDidMount componentDidUpdate and componentWillUnmount A combination of.

By default, useEffect Will be After the first rendering and After each update Execute, every run useEffect The DOM has been updated.

To control useEffect The second optional parameter can be used to control the execution time and times of.

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

Pass an empty array ([]) as the second parameter. This effect will never be repeated, so it can achieve componentDidMount The effect of.

useEffect It can return a function that will be executed when the component is unloaded, which can be equivalent to componentWillUnmount

 function AComponent(){ React.useEffect(()=>{ console.log("componentDidMount"); // Return function cleanup() {console. log ("The component is uninstalled componentWillUnmount")}; },[]); }

Other Precautions for Hook

See reactjs.org/HooksFAQ

Zimiao haunting blog (azimiao. com) All rights reserved. Please note the link when reprinting: https://www.azimiao.com/6729.html
Welcome to the Zimiao haunting blog exchange group: three hundred and thirteen million seven hundred and thirty-two thousand

Comment

*

*

Comment area

  1. calmly 10-16 14:36 reply

    Thank you, it's helpful