我们如何使用React的Suspense
和React.lazy
来延迟加载<img>
并在下载图像时显示骨架占位符?
尝试以下操作无济于事:
import React, { Component, Suspense } from 'react';
const LazyImage = ({src}) => {
const LazyImg = React.lazy((src) => <img src={src} />);
return (
<Suspense fallback={<span>Loading Placeholder</span>}>
<LazyImg src={src} />
</Suspense>
)
}
class Foo extends Component {
render() {
return (
<LazyImage src="https://149351115.v2.pressablecdn.com/wp-content/uploads/2018/05/SO_Teams-1200x675.png" />
)
}
}
发生的错误是
react-dom.development.js:19527 The above error occurred in one of your React components:
in Unknown (created by LazyLoadImg)
in Suspense (created by LazyLoadImg)
in LazyLoadImg (created by GalleryComponent)
in div (created by GalleryComponent)
in div (created by GalleryComponent)
in GalleryComponent (created by ConnectFunction)
in ConnectFunction (created by Gallery)
in div (created by Row)
in Row (created by Gallery)
in Gallery (created by ConnectFunction)
in ConnectFunction (created by Context.Consumer)
in Route (created by PrivateRouteHandler)
in PrivateRouteHandler (created by ConnectFunction)
in ConnectFunction (created by Context.Consumer)
in withRouter(Connect(PrivateRouteHandler))
in div (created by MainLayout)
in div (created by MainLayout)
in MainLayout
in Route
in Router (created by ConnectedRouter)
in ConnectedRouter (created by Context.Consumer)
in ConnectedRouterWithContext (created by ConnectFunction)
in ConnectFunction
in Provider
使用react@16.13.1
,react-dom@16.13.1
和节点v14