React Hooks实现组件生命周期

#积累/react/react-hooks#

生命周期方法

::挂载::

  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()
    ::更新::
  • static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()
    ::卸载::
  • componentWillUnmount()

constructor

函数组件不需要

render

函数组件return的内容即要渲染的UI

componentDidMount

第二个参数为空数组,不依赖于任何状态,只会在挂载和卸载时执行一次。

1
2
3
4
5
6
7
8
9
function useMount(fn) {
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(friendID,
handleStatusChange);
}, [])
}

componentWillUnmount

useEffect第一个参数如果返回一个函数,则改函数会在组件卸载前执行。

1
2
3
4
5
6
7
8
9
10
11
function useUnmount(fn) {
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}

return () => {
ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);
};
},[]);
}

componentDidUpdate

useRef的作用:

useRef返回一个可变的 ref 对象,其.current属性被初始化为传入的参数(initialValue)。返回的 ref 对象在组件的整个生命周期内保持不变。
=> 类似于class组件中的this.timerId

  • 使用useRef,获取DOM节点
    React 会在组件挂载时给current属性传入 DOM 元素

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    function TextInputWithFocusButton() {
    const inputEl = useRef(null);
    const onButtonClick = () => {
    // `current` 指向已挂载到 DOM 上的文本输入元素
    inputEl.current.focus();
    };
    return (
    <>
    <input ref={inputEl} type="text" />
    <button onClick={onButtonClick}>Focus the input</button>
    </>
    );
    }
  • 使用useRef,创建可变变量

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    function useUpdate(fn) {
    const mounting = useRef(true)

    useEffect(() => {
    if (mounting.current) {
    mounting.current = false
    } else {
    fn()
    }
    })
    }

    https://medium.com/@dispix/from-react-component-to-hooks-b50241334365