如果没有部门,为什么以及何时应该使用效果?
(与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;
}
答案 0 :(得分: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
。但是,您无法设置状态或执行会导致重新渲染的操作,否则您的应用将陷入循环