nextTick
函数,这是一个等待 DOM 刷新的异步函数。当您想要直接对元素执行某些操作(例如使用 scroll()
滚动 DIV)时,这特别有用。这样就无需将此调用包装为盲调用 setTimeout()
。
在 React 中我过去使用过
setTimeout()
。有相当于 nextTick()
的东西,或者有更好的方法吗?
在这种情况下,可以使用
setTimeout
来实现此目标。
请参阅:https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#late_timeouts
因为它会在当前线程的末尾执行参数中给出的函数,所以它接近
Vue.nextTick
的行为。
示例:https://codesandbox.io/s/gallant-roman-y0b9un?file=/src/App.js
您可以使用
reactHooks
来处理应用程序的生命周期。
在您的功能组件中:
import React, { useEffect } from 'React'
useEffect(() => {
// your method
}, []);
这将在第一次渲染中渲染。
您可以设置依赖项发生变化时监听。
import React, { useEffect } from 'React'
useEffect(() => {
// your method
}, [yourDependence]); //it will run every yourDependence change and the first time.
在 React 类组件中,您可以使用
componentDidMount
进行第一次渲染,使用 componentDidUpdate
进行后续渲染,以执行 DOM 更新。
componentDidMount
需要 DOM 节点的初始化应该放在这里。
参见https://reactjs.org/docs/react-component.html#componentdidmount
componentDidUpdate
当组件更新时,以此为契机对 DOM 进行操作。
参见https://reactjs.org/docs/react-component.html#componentdidupdate
对于功能组件,有
useEffect
钩子。
使用
setTimeout
对我来说不起作用,因为我需要运行一个关闭 props 的函数,这意味着该函数的过时版本将在给定的超时后运行。
这就是我想出的:
const useEffectOnNextRender = (callback: React.EffectCallback) => {
const [scheduled, setScheduled] = useState(false);
useEffect(() => {
if (!scheduled) {
return;
}
setScheduled(false);
callback();
}, [scheduled]);
return () => setScheduled(true);
};
这是使用这个钩子的方法:
function DemoComponent() {
const [count, setCount] = useState(0);
const scheduleDisplay = useEffectOnNextRender(() => {
display();
});
const incrementAndDisplay = () => {
setCount(count + 1);
scheduleDisplay();
};
const display = () => {
console.log(count);
};
return (
<div>
<div>{count}</div>
<button onClick={incrementAndDisplay}>increment and display</button>
</div>
);
}
注意
scheduleDisplay()
函数中的 incrementAndDisplay
调用。如果我只是调用 display()
,则会记录 count
变量的过时值。
显然这是一个过于简化的例子,只是为了证明这一点。
我想分享一下,也许将来会对某人有所帮助。