如何使用 React hooks 等待子组件 "ready"?

How do I wait for child components to be "ready" with React hooks?

所以我有一个 Page 组件,其中包含多个 Column 组件,每列包含不同的用户特定标记。

Page 组件中,我需要做一些额外的更改(例如列溢出检查、推送列内容等)。出于这个原因,我需要一种在所有 Column 组件都已安装后得到通知的方法 - 还包括已进行的隐式突变。

我的第一次尝试是 useEffect 挂钩,但是,它确实在 Column 组件收到它之前被调用 ref

// AppContext
const [columns, setColumns] = useState([]);

const Page = ({children}) => {
    useEffect({
       // This gets called before columns are available
    }, []);

    return (<div className="page">{children}</div>);
}

const View = () => {
    const {columns} = useContext(AppContext);

    return (
        <Page>
            {columns.map(c => <Column>{c}</Column>)}
        </Page>
    );
}

实际上,基于 ReactJS docs 有一个与 useEffect 完全相同的钩子,但它在所有 DOM 突变之后调用它的回调,那个名字是 useLayoutEffect:

The signature is identical to useEffect, but it fires synchronously after all DOM mutations. Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside useLayoutEffect will be flushed synchronously before the browser has a chance to paint.

我更喜欢使用 useEffect,因为基于文档,使用 useLayoutEffect 可能会导致渲染阻塞问题。

对于您的特殊情况,您可以使用 useLayoutEffect