解决 Hydration failed because the initial UI does not match what was rendered on the server

16 min read
import React, {FC, useEffect, useState} from 'react';
import { createPortal } from 'react-dom'
type Props = {
    title: string;
    children?: React.ReactNode;
    onClose: () => void;
};
const PortalComponent:FC<Props> = ({ children,title, onClose }) => {
    const [isSSR, setIsSSR] = useState(true);
    useEffect(() => {
        setIsSSR(false);
    }, []);
    return isSSR?null:createPortal(
        <div className="modal"  onClick={onClose}>
            <h1>{title}</h1>
            {children}
        </div>,document.getElementById('portal')!
        )
};

需要判断是否SSR 环境