0

我想知道使用 React Lazy 和 Supense 与我在下面展示的内容相比有哪些好处。第一个示例是使用 useState 和 Onload Prop,第二个示例是使用 React Lazy 和 Suspense。

const ImageComponent = ({ src }) => {
    const [load, setLoad] = useState(false);

    //handles load of the image
    const handleOnload = () => {
        setLoad(true);
    };

    return (
        <>
            {!load && <Spinner>}
            <img
                src={src}
                alt="Avatar"
                onLoad={handleOnload}
                style={{
                    height: '192px',
                    width: '50%',
                    display: load ? 'inline' : 'none',
                }}
            />
        </>
    );
};

VS这个

        <Suspense
                fallback={
                    <Spinner style={{ width: '50%' }} />
                }
            >
            <ImageComponent src={listItem.download_url} />
        </Suspense>

ImageComponent.js

const ImageComponent = ({ src }) => {
    return (
        <img
            src={src}
            alt="Avatar"
            style={{
                height: '192px',
                width: '50%',
            }}
        />
    );
};

export default ImageComponent;
4

0 回答 0