繁体   English   中英

与使用 react hooks 的先前状态实现相关的问题

[英]Question related to previous state implementation using react hooks

这是 react 的网站建议实施的方式:

https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state

我的问题是,我们可以使用useState而不是useRef吗?

如果是,它与useRef实现有什么不同吗?

function Counter() {
  const [count, setCount] = useState(0);
  const prevCount = usePrevious(count);
  return <h1>Now: {count}, before: {prevCount}</h1>;
}

function usePrevious(value) {
  // can we use "useState" instead of "useRef" here?
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}

可以,例如

function Counter() {
  const [count, setCount] = useState(0);
  const [prevCount, setPrevCount] = useState();
  const setCountAndPrev = (newCount) => {
    setCount(newCount);
    setPrevCount(count);
  };

然后继续使用setCountAndPrev (如果需要,可以将整个内容提取到另一个钩子中)-但这有点令人费解。

如果没有同时设置两个状态,则可能效率低下,因为状态设置会导致重新渲染,在不必要时应避免这种情况。 这通常不是问题,但它可能被认为更优雅。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM