如果我没有deps,为什么以及何时应该使用效果?
(来自React Docs(有什么区别:
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
且无用效果?
function usePrevious(value) {
const ref = useRef();
ref.current = value;
return ref.current;
}
这两种方法的差异是在渲染周期完成后运行useEffect
,因此参考将保持先前的值,而在第二种方法中,您的参考文献将为立即更新,因此上一个始终将等于当前值
样品示例
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
而无需依赖。但是,您无法设置状态或执行将导致重新渲染的操作,否则您的应用将进入循环