簡體   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