A, create,

const App = (props) = >{
    return <div>{props.message}</div>
}
Copy the code

Problems with function components:

  • No state —- React v16.8.0 release Hooks API, useuseStateTo solve
  • No lifecycle —- Hooks API, useuseEffectTo solve

Second, the state

Using useState

const App = props= > {
    const [n, setN] = React.useState(0)
    return / /...
}
Copy the code

Life cycle

Using useEffect

UseEffect accepts two arguments: useEffect(fn, arR)

1, simulation,componentDidMount

useEffect(fn, []) // The second argument is an empty array and fn is called only after the first rendering
Copy the code

2, simulation,componentDidUpdate

useEffect(fn, [n, m]) // Call fn for the first rendering and data changes in the array
useEffect(fn) // Fn is called for the first rendering and any data changes
Copy the code

Question: If fn is called on the first render, how can it be called only after the data is updated?

Solution: Add condition judgment in fn, use a variable to record the number of n updates, the number of times >1, then perform the operation

const [nUpdateCount, setNUpdateCount] = useState(0)

useEffect(() = >{
    setNUpdateCount(x= >x+1)
}, [n])
useEffect(() = >{
    if(nUpdateCount > 1) {console.log('n changed')
    }
}, [nUpdateCount])
Copy the code

Optimise: define a Hook to encapsulate the above code as a useUpdate function, useUpdate(fn, n) means that fn is called only when n is updated

const useUpdate = (fn, dep) = >{
    const [count, setCount] = useState(0)
    useEffect(() = >{
        setCount(x= > x+1)
    }, [dep])
    useEffect(() = >{
        if(count>1){
            fn()
        }
    }, [count, fn])
}
Copy the code

3, simulation,componentWillUnmount

UseEffect (fn), the function returned by FN is executed when the component is destroyed, namely:

useEffect(() = >{
    return () = >{/ *... * /}})Copy the code

[example]

To simulate the destruction of a component, click the button to destroy the Child component:

const App = props= > {
  const [childVisible, setChildVisible] = React.useState(true)
  const show = () = >{setChildVisible(true)}
  const hide = () = >{setChildVisible(false)}
  return (
    <div>
      {childVisible?
		<button onClick={hide}>hidden</button>:
		<button onClick={show}>According to</button>}
      {childVisible?<Child />:null}
    </div>)}const Child = props= > {
  useEffect(() = >{
    return () = >{console.log('Child destroyed')}})return (
    <div>I am a child</div>)}Copy the code

4, simulation,shouldComponentUpdate

Use react. memo and useMemo. See later