美文网首页
了解React Hooks 模拟生命周期

了解React Hooks 模拟生命周期

作者: 舞鹤Roc | 来源:发表于2021-07-16 17:10 被阅读0次

在React官方大力推荐使用函数式编程的同时,引入 Hooks ,让组件在不使用 class 的情况下拥有 state,所以就有了生命周期的概念。下面让我们一探 Hooks 究竟。

官方定义

Hook 是一些可以让你在函数组件里“钩入” React state 及生命周期等特性的函数。

谁拥有生命周期?

React的生命周期是关于组件的,包括 React.ComponentReact.PureComponent ,以及Hooks 组件。

React.PureComponent 与 React.Component 几乎完全相同,但 React.PureComponent 通过props和state的浅对比来实现 shouldComponentUpate()。

Hooks组件就是使用了Hooks的函数组件,而函数组件本质是一个 render 函数而已,没有 state ,不存在生命周期。

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

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
)

说明:React.memo 包裹一个组件来对它的 props 进行浅比较,但这不是一个 hooks,因为它的写法和 hooks 不同,其实React.memo 等效于 PureComponent,但它只比较 props。

总结:

class 组件 Hooks 组件
constructor useState
getDerivedStateFromProps useState 里面 update 函数
shouldComponentUpdate useMemo
render 函数本身
componentDidMount useEffect空数组或固定值
componentDidUpdate useEffect
componentWillUnmount useEffect 里面返回的函数
componentDidCatch
getDerivedStateFromError

附一张React生命周期图:


v16.4

相关文章

网友评论

      本文标题:了解React Hooks 模拟生命周期

      本文链接:https://www.haomeiwen.com/subject/csubpltx.html