Why do WE need a class component?
1. Need state
2. Life cycle functions are required
3. Side effects required (Ajax)
However, Hooks can implement the syntax above
The Hooks API
useState
const [ count, setCount ] = useState(0)Copy the code
Create a state of count. Default is 0. Use setCount to change the state of count.
Each time useState is called, a space is allocated for storing state values. React identifies Spaces by the order in which useState is called
State cannot be added, and the order will change, such as:
const Counter = () => {
const [ count, setCount ] = useState(0);
if(count === 0) {const [name,setName ] = useState('momo'); } const [ sex,setSex ] = useState('woman');
}Copy the code
The first time react is called, three Spaces will be allocated to store react. When count changes, only two Spaces will be allocated to store react
useEffect
componentDidmount componentDidUpdate
UseEffect (() => {// every time mount or update})Copy the code
componentDidmount
UseEffect (() => {// only mount call}, [])Copy the code
componentWillUnMount
UseEffect (() => {// Only mount callsreturn() => {// componentWillUnMount}}, [])Copy the code
componentDidUpdate
const mounted = useRef();
useEffect = (() => {
if(! mounted.current){ mounted.current =true;
} else {
// componentDidUpdate
})Copy the code
The second argument to useEffect is the dependent data, which is executed if the array data changes and not if it does not
useContext
.
Hooks have the same naming convention as all HOC useXXX;
Each execution has its own props and state