React 是否有相当于 Vue 的 nextTick() 函数?

问题描述 投票:0回答:5

Vue 有这个

nextTick
函数,这是一个等待 DOM 刷新的异步函数。当您想要直接对元素执行某些操作(例如使用
scroll()
滚动 DIV)时,这特别有用。这样就无需将此调用包装为盲调用
setTimeout()

在 React 中我过去使用过

setTimeout()
。有相当于
nextTick()
的东西,或者有更好的方法吗?

javascript reactjs vue.js dom
5个回答
10
投票

在这种情况下,可以使用

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


6
投票

您可以使用

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.

1
投票

在 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
钩子。

参见https://reactjs.org/docs/hooks-effect.html


0
投票

使用

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
变量的过时值。

显然这是一个过于简化的例子,只是为了证明这一点。

我想分享一下,也许将来会对某人有所帮助。


0
投票

迟到的回复:

现在,您可以使用 JavaScript 中名为queueMicrotask 的本机方法,请在此处阅读更多信息

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