reactjs – 代码拆分导致在SPA的新部署后无法加载块
我有一个单页应用程序,我在每条路线上编码拆分.当我部署新版本的应用时,如果用户仍然打开该页面并访问之前未访问过的路由,则用户通常会收到错误.
另一种情况是,如果应用程序启用了服务工作程序,也会发生这种情况.当用户在新部署后访问页面时,服务工作者将从缓存中提供服务.然后,如果用户尝试访问不在其缓存中的页面,则他们将获得块加载失败. 目前我在我的应用程序中禁用了代码拆分以避免这种情况,但我一直很好奇处理这个问题的最佳方法是什么.我已经考虑过在用户完成加载初始页面后预加载所有其他路由,我相信这可能会解决路由上代码拆分的问题.但是,假设我想对组件进行代码拆分,那么这意味着我必须设法确定何时以及如何预加载所有这些组件. 所以我想知道人们如何处理单页应用程序的这个问题?谢谢! (我目前正在使用create-react-app) 解决方法
我们用一个稍微丑陋的解决方案解决了这个问题现在可能是暂时的,但可能对某人有所帮助.
我们创建了一个AsyncComponent来加载块(即路由组件).当这个组件加载一个块并接收并发生错误时,我们只需要一个简单的页面重新加载来更新index.html,它就是对主块的引用.丑陋的原因在于,根据页面的外观或加载方式,用户可以在刷新前看到短暂的空白页面.它可能有点刺耳,但也许这也是因为我们不希望SPA自发刷新. App.js // import the component for the route just like you would when // doing async components const ChunkedRoute = asyncComponent(() => import('components/ChunkedRoute')) // use it in the route just like you normally would <Route path="/async/loaded/route" component={ChunkedRoute} /> asyncComponent.js import React,{ Component } from 'react' const asyncComponent = importComponent => { return class extends Component { state = { component: null,} componentDidMount() { importComponent() .then(cmp => { this.setState({ component: cmp.default }) }) .catch(() => { // if there was an error,just refresh the page window.location.reload(true) }) } render() { const C = this.state.component return C ? <C {...this.props} /> : null } } } export default asyncComponent (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |