什么时候使用useEffect没有deps?

问题描述 投票:1回答:1

如果我没有deps,为什么以及何时应该使用效果?

(来自React docs)有什么区别:

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}

并且没有useEffect?

function usePrevious(value) {
  const ref = useRef();

  ref.current = value;

  return ref.current;
}
reactjs react-hooks
1个回答
1
投票

两种方法的不同之处在于useEffect在渲染周期完成后运行,因此ref.current将保持先前的值,而在第二种方法中,ref.current将立即更新,因此前一个将始终等于当前的价值

示例演示

const {useRef, useEffect, useState} = React;
function usePreviousWithEffect(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}

function usePrevious(value) {
  const ref = useRef();

  ref.current = value;

  return ref.current;
}
const App = () => {
   const [count, setCount] = useState(0);
   const previousWithEffect = usePreviousWithEffect(count);
   const previous = usePrevious(count);
   
   return (
      <div>
        <div>Count: {count}</div>
        <div>Prev Count with Effect: {previousWithEffect}</div>
        <div>Prev Count without Effect: {previous}</div>
        <button type="button" onClick={() => setCount(count => count + 1)}>Increment</button>
      </div>
   )
}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="app"/>

另外,为了回答你的问题,当你想对每个渲染执行一些操作时,你可以无依赖地传递useEffect。但是,您无法设置状态或执行将导致重新渲染的操作,否则您的应用将进入循环

© www.soinside.com 2019 - 2024. All rights reserved.