如何通过Hooks模拟react的生命周期

208 阅读1分钟

转发 www.jianshu.com/p/5dfe9a104…

constructor

function Example() {
  // 在函数里初始化state
  const [count, setCount] = useState(0);
  return null;
}

componentDidUpdate / componentDidMount

function Example() {
  // componentDidUpdate
  useEffect(() => console.log('mounted or updated'));
  // componentDidMount
  useEffect(() => console.log('mounted'), []);
  return null;
}

说明:useEffect 拥有两个参数,第一个参数作为回调函数会在浏览器布局和绘制完成后调用,因此它不会阻碍浏览器的渲染进程。第二个参数是一个数组:

  • 当数组存在并有值时,如果数组中的任何值发生更改,则每次渲染后都会触发回调。
  • 当它不存在时,每次渲染后都会触发回调,类似于 componentDidUpdate。
  • 当它是一个空列表时,回调只会被触发一次,类似于 componentDidMount。

shouldComponentUpdate

const MyComponent = React.memo(
    _MyComponent, 
    (prevProps, nextProps) => nextProps.count !== prevProps.count
)
class 组件Hooks 组件
constructoruseState
getDerivedStateFromPropsuseState 里面 update 函数
shouldComponentUpdateuseMemo
render函数本身
componentDidMountuseEffect空数组或固定值
componentDidUpdateuseEffect
componentWillUnmountuseEffect 里面返回的函数
componentDidCatch
getDerivedStateFromError

image.png