首页 > 解决方案 > useRef 如何用于存储先前的状态

问题描述

function Counter() {
  const [count, setCount] = useState(0);

  const prevCountRef = useRef();
  useEffect(() => {
    prevCountRef.current = count;  });
  const prevCount = prevCountRef.current;
  return <h1>Now: {count}, before: {prevCount}</h1>;
}

在上面的代码片段中,React Hoks FAQS useRef用于保存计数。但是,每当调用 render 时,不会prevCount将 设置为当前count,因为useEffect将在每次渲染时调用,那么 count 和 prevCount 有何不同?

标签: reactjsreact-hooks

解决方案


这是因为useEffect回调函数会在 Component 完成后被rendering time调用Counter。这就是为什么prevCount总是tick落后。

需要考虑的一点是,a 中的更改React ref不会导致 React 组件中的重新渲染,只会change in state and props导致重新渲染。

在此处查看工作示例:https ://codesandbox.io/s/lucid-butterfly-y66tc?file=/src/App.js

export default function Counter() {
  const [count, setCount] = useState(0);

  const prevCountRef = useRef();
  useEffect(() => {
    prevCountRef.current = count;
    console.log('me socond')
  });
  console.log('me first')
  const prevCount = prevCountRef.current;
  return (
    <h1>
      Now: {count}, before: {prevCount}
      <div onClick={() => setCount((v) => v + 1)}>click me</div>
    </h1>
  );
}

me first然后me second在控制台中看到


推荐阅读