我有一个需要一段时间才能加载的组件 . 实际上,它是一个加载另一个网站 <iframe>
的组件,需要一段时间才能加载 .
我希望组件能够挂载并因此运行加载iframe的componentDidMount代码块,这样当用户单击'create'选项卡时,用户立即在页面的 <main>
部分中看到iframe .
有没有办法指示react-router到 pre-load the component ,同时在路由更改时保留相同的条件呈现逻辑并保留呈现组件页面上的位置?
这是我在应用程序根目录上的 render()
语句,为您提供一些上下文:
render() {
return (
<div className="App">
<Nav />
<Snackbar
open={this.props.snackbar.get().open}
message={this.props.snackbar.get().message}
autoHideDuration={4000}
onRequestClose={() => this.handleSnackbarRequestClose()}
/>
<TreeViewer />
<PayloadListener/>
<main>
<ThankYouModal open={this.props.showConfirmationModal.get()} handleClose={ () => this.props.showConfirmationModal.set(false) }/>
<Switch>
<Route path="/imageservices" component={ImageServicesController} />
<Route path="/create" component={Iframe} />
<Route exact path="/account" component={Account} />
<Route exact path="/analytics" component={AnalyticsController} />
<Route path="/support" component={SupportView} />
<Route path='/login' render={ (props) => <Login { ...props } /> } />
<Route path='/logout' render={ (props) => <Logout { ...props } /> } />
</Switch>
</main>
</div>
);
}
这是我希望React Router预加载的组件:
<Route path="/create" component={Iframe} />
我怎样才能做到这一点?
2 回答
不是通过react-router,但你可以在
index.html
中使用link
preload
as
document
来确保浏览器延迟加载文档 . 它's intended purpose is to preload documents which can then be displayed in iframe. You also won' t需要改变你的路由器机制 .在这里阅读更多相关信息 - https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content .
基本上,只需将其添加到
index.html
的head
:<link rel='preload' href='your_iframe_url' as='document'>
好吧,如果你看一下React component lifecycle,你可以看到 render 总是在 componentDidMount 之前运行 . 因此,如果没有渲染它,您将无法安装组件 .
这些是安装时调用的生命周期方法:
constructor()
static getDerivedStateFromProps()
render()
componentDidMount()
你可以尝试一些事情:
您可以轻松地为iframe的 load 事件添加eventListener,并在状态更改时对其进行适当的更改以淡入淡出 .
您可以将其添加到文档的头部:
然后通常使用你的iframe:
如果您的iframe网址是动态的,并且依赖于经过身份验证的用户的某些信息,并且您无法立即将其放入html文件中,请记住,只要您拥有所需的信息,就可以始终使用react-helmet将其呈现为head标记 .