介绍

  1. 生命周期可以说是开发最重要的一环,主要介绍下:useMount(装载)、useUnmount(卸载)、 useUpdateEffect(更新)、 useUpdateEffect(强制更新)、 useTrackedEffect(依赖)、 useDebounceEffect(防抖)、 useThrottleEffect(节流)

在线演示: Domesy/LifeCycle

装载与卸载

useMount:组件装载的时候调用,类似于 class 组件的 componentDidMount
useUnmount:组件卸载的时候调用,类似于 class 组件的 componentWillUnmount

代码演示

image.png
image.png

详细代码

  1. import React from 'react';
  2. import { Button, message } from 'antd';
  3. import { useToggle, useMount, useUnmount } from 'ahooks';
  4. const Test = () => {
  5. useMount(() => {
  6. message.info('装载');
  7. });
  8. useUnmount(() => {
  9. message.info('卸载');
  10. });
  11. return <div>初始页面</div>;
  12. };
  13. const Mock: React.FC<any> = () => {
  14. const [state, { toggle }] = useToggle(false);
  15. return (
  16. <>
  17. <button type="button" onClick={() => toggle()}>
  18. {state ? '卸载' : '装载'}
  19. </button>
  20. {state && <Test />}
  21. </>
  22. );
  23. };
  24. export default Mock;

更新

useUpdateEffect 在使用的时候与 useEffect 一致,不同时是 忽略了首次渲染

代码演示

image.png

详细代码

  1. import React, { useState, useEffect } from 'react';
  2. import { Button, message } from 'antd';
  3. import { useUpdateEffect } from 'ahooks';
  4. const Mock: React.FC<any> = () => {
  5. const [count, setCount] = useState(0);
  6. const [effectCount, setEffectCount] = useState(0);
  7. const [updateEffectCount, setUpdateEffectCount] = useState(0);
  8. useEffect(() => {
  9. setEffectCount((c) => c + 1);
  10. }, [count]);
  11. useUpdateEffect(() => {
  12. setUpdateEffectCount((c) => c + 1);
  13. }, [count]);
  14. return (
  15. <>
  16. <p>使用Effect: {effectCount}</p>
  17. <p>使用updateEffectCount: {updateEffectCount}</p>
  18. <Button type='primary' onClick={() => setCount((c) => c + 1)}>
  19. 渲染
  20. </Button>
  21. </>
  22. );
  23. };
  24. export default Mock;

强制更新

useUpdate 强制更新当前组件

代码演示

image.png

详细代码

  1. import React from 'react';
  2. import { Button } from 'antd';
  3. import { useUpdate } from 'ahooks';
  4. const Mock: React.FC<any> = () => {
  5. const update = useUpdate();
  6. return (
  7. <>
  8. <p>时间: {Date.now()}</p>
  9. <Button type='primary' onClick={() => update()}>
  10. 强制更新
  11. </Button>
  12. </
  13. };
  14. export default Mock;

依赖改变

当做一个比较复杂的功能时,我们所依赖的参数较多,我们可能需要做某一项依赖改变的时候才进行触发,这是就有一个非常棒的Api来帮助我们,就是 useTrackedEffect

  • changes:第几个依赖项发生了改变
  • previousDeps:依赖项当前的值
  • currentDeps:依赖项改变后的值

    代码演示

    image.png

    详细代码

    1. import React, { useState } from 'react';
    2. import { Button } from 'antd';
    3. import { useTrackedEffect } from 'ahooks';
    4. const Mock: React.FC<any> = () => {
    5. const [dep1, setDep1] = useState(0);
    6. const [dep2, setDep2] = useState(0);
    7. const [dep3, setDep3] = useState(0);
    8. const [depActiveList, setDepActiveList] = useState([false, false, false]);
    9. const [text, setText] = useState('第几个依赖项改变:')
    10. const [text1, setText1] = useState('当前的值:')
    11. const [text2, setText2] = useState('改变后的值:')
    12. const toggleDep = (index:number) => {
    13. const res = [...depActiveList];
    14. res[index] = !res[index]
    15. setDepActiveList(res)
    16. }
    17. useTrackedEffect((changes:[], previousDeps:[], currentDeps:[])=>{
    18. setText('第几个依赖项改变:: ' + changes);
    19. setText1('当前的值:: ' + previousDeps);
    20. setText2('改变后的值:: ' + currentDeps);
    21. },[dep1, dep2, dep3])
    22. return (
    23. <>
    24. <p><input type="checkbox" checked={depActiveList[0]} onChange={() => toggleDep(0)} />
    25. &nbsp;第一个值 : {dep1}</p>
    26. <p>
    27. <input type="checkbox" checked={depActiveList[1]} onChange={() => toggleDep(1)} />
    28. &nbsp;第二个值 : {dep2}
    29. </p>
    30. <p>
    31. <input type="checkbox" checked={depActiveList[2]} onChange={() => toggleDep(2)} />
    32. &nbsp;第三个值 : {dep3}
    33. </p>
    34. <Button type='primary' onClick={() => {
    35. setText('')
    36. setText1('')
    37. setText2('')
    38. depActiveList[0] && setDep1((c) => c + 1);
    39. depActiveList[1] && setDep2((c) => c + 1);
    40. depActiveList[2] && setDep3((c) => c + 1);
    41. }}>
    42. 1
    43. </Button>
    44. <p>{text}</p>
    45. <p>{text1}</p>
    46. <p>{text2}</p>
    47. </>
    48. );
    49. };
    50. export default Mock;

    防抖

    seDebounceEffect: 增强 effect 的防抖能力

    代码演示

    image.png

    详细代码

    1. import React, { useState } from 'react';
    2. import { useDebounceEffect } from 'ahooks';
    3. const Mock: React.FC<any> = () => {
    4. const [value, setValue] = useState<string>('hello');
    5. const [records, setRecords] = useState<string[]>([]);
    6. useDebounceEffect( () => {
    7. setRecords((val) => [...val, value]);
    8. },
    9. [value],
    10. {
    11. wait: 1000,
    12. },
    13. );
    14. return (
    15. <>
    16. <input
    17. value={value}
    18. onChange={(e) => setValue(e.target.value)}
    19. placeholder="Typed value"
    20. style={{ width: 280 }}
    21. />
    22. <p style={{ marginTop: 16 }}>
    23. <ul>
    24. {records.map((record, index) => (
    25. <li key={index}>{record}</li>
    26. ))}
    27. </ul>
    28. </p>
    29. </>
    30. );
    31. };
    32. export default Mock;

    节流

    useThrottleEffect: 增强 effect 的节流能力

    代码演示

    image.png

    详细代码

    1. import React, { useState } from 'react';
    2. import { useThrottleEffect } from 'ahooks';
    3. const Mock: React.FC<any> = () => {
    4. const [value, setValue] = useState<string>('hello');
    5. const [records, setRecords] = useState<string[]>([]);
    6. useThrottleEffect( () => {
    7. setRecords((val) => [...val, value]);
    8. },
    9. [value],
    10. {
    11. wait: 1000,
    12. },
    13. );
    14. return (
    15. <>
    16. <input
    17. value={value}
    18. onChange={(e) => setValue(e.target.value)}
    19. placeholder="Typed value"
    20. style={{ width: 280 }}
    21. />
    22. <p style={{ marginTop: 16 }}>
    23. <ul>
    24. {records.map((record, index) => (
    25. <li key={index}>{record}</li>
    26. ))}
    27. </ul>
    28. </p>
    29. </>
    30. );
    31. };
    32. export default Mock;