正在将React.lazy对象转换为JSX元素



我有一个名为GoogleMap.js的组件。如果用户滚动,我想导入它,所以我让它延迟导入,但它不返回JSX。相反,它返回React.lazy对象。所以我无法在JSX中呈现它。如何在JSX中渲染它。此外,如果我这样使用它,它是否会导入react谷歌地图,即使使用不会滚动页面。

import React from 'react'
import GoogleMapReact from 'google-map-react'
import styled from 'styled-components'
const GoogleMapWrapper = styled.div`
height: 40vh; 
width: 60vw;
margin: 50px auto;
border: 1px solid red;
`
function GoogleMap() {
return (
<GoogleMapWrapper>
<GoogleMapReact
bootstrapURLKeys={{ key: 'AIzaSyAER*******************zs0' }}
defaultCenter={{
lat: -3.745,
lng: -38.523
}}
defaultZoom={3}
>
<div
lat={59.955413}
lng={30.337844}
text="My Marker"
/>
</GoogleMapReact>
</GoogleMapWrapper>
)
}
export default GoogleMap
useEffect(() => {
if (isImported) {
window.removeEventListener('scroll', scrollDetector)
const GoogleMap = React.lazy(() => import('../../components/DynamicLandingPages/GoogleMap'))
console.log("type:", typeof GoogleMap)
console.log("OBJ:", GoogleMap)
setGoogleMapComponent(GoogleMap)
}
}, [isImported])

注意:googleMapComponent是一个反应状态。Set是它的setter函数。

<Suspense fallback={<GoogleMapWrapper />}>
<googleMapComponent />
</Suspense>

以下是它返回的内容:

{$$typeof: Symbol(react.lazy), _status: -1, _result: null, _ctor: ƒ, …}

您正在滥用React状态。您不应该将组件保持为状态!此外,这个<googleMapComponent />是错误的。更多详细信息,请参阅文档。

最后,在useEffect中使用React.lazy有什么原因吗?

它应该这样使用:

// some MyComponent.js file
// ... normal imports ...
const GoogleMap = React.lazy(() => import('../../components/DynamicLandingPages/GoogleMap'));
function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<GoogleMap />
</Suspense>
</div>
);
}

如果你需要在滚动到某个位置时渲染一些东西,而不是添加一些状态,比如isElementInViewport,你需要一段JS来真正弄清楚这一点,并在它发生时将该状态设置为true,然后你可以做一些事情,比如:

{isElementInViewport  
&& (Suspense fallback={<div>Loading...</div>}>
<GoogleMap />
</Suspense>)}

最新更新