react函数组件怎么获取上一次的props和state

1,246 阅读1分钟

hooks中通过useRef和useEffect获取上一次的props和state

看一下官方文档对useRef的描述

useRef

image.png

注意: 当ref对象内容发生变化时,是不会引发组件重新渲染的;

在看一下官方对useEffect的解释:

image.png

他会在浏览器完成布局与绘制之后,在一个延迟事件中被调用.

结合useRef和useEffect,我们就能够获取到上一次的props和state;

function PrevState() {
  const [count, setCount] = React.useState(0);

  const prevCountRef = React.useRef();
  React.useEffect(() => {
    prevCountRef.current = count;
  });
  const handleClick = () => {
    setCount(count+1)
  }
  return (
    <>
      <button onClick={handleClick}>+1</button>
      <h1>Now: {count}, before: {prevCountRef.current}</h1>
    </>
  )
}

最初渲染过程: count =0;

页面: Now: 0,before:

执行useEffect, prevCountRef.current=0;

因为ref对象内容变化不会引发组件重新渲染,所以prevCountRef.current的值变了, 页面依旧是: //Now: 0,before:

当点击按钮 count +1 的时候,

触发handleClick函数,count +1;

count 发生变化, 组件重新渲染;

页面: Now: 1,before: 0

触发useEffect,prevCountRef.current= 1

ref对象发生变化,不会重新渲染;

页面: //Now: 1,before: 0

至此搞懂了在函数组件中怎么获取上一次的props和state