[英]Is there a way to avoid blanks in react loadable components
I am using the react Loadable Components Package to lazily load components in my react app as shown in the snippet below:我正在使用React Loadable Components Package在我的 React 应用程序中延迟加载组件,如下面的代码片段所示:
import loadable from '@loadable/component'
const OtherComponent = loadable(() => import('./OtherComponent'))
function MyComponent() {
return (
<div>
<OtherComponent />
</div>
)
}
The site is hosted on firebase hosting.该站点托管在 firebase 主机上。
I noticed that sometimes the lazily imported component won't load until the page is refreshed manually.我注意到有时延迟导入的组件在手动刷新页面之前不会加载。
On checking the logs I can see errors like在检查日志时,我可以看到类似的错误
Chunk Failed to load
区块加载失败
Once I refresh the page, the page gets loaded and the Chunk Failed to Load error is gone.一旦我刷新页面,页面就会被加载并且块加载失败错误消失了。
Is there a way to avoid this?有没有办法避免这种情况?
You can have a retry(...)
function. It wont make the problem completely disappear, but at least it will add some resilience upon failures:你可以
retry(...)
function。它不会使问题完全消失,但至少它会在失败时增加一些弹性:
export function retry(
fn,
{retries = 4, interval = 500, exponentialBackoff = true} = {}
) {
return new Promise((resolve, reject) => {
fn()
.then(resolve)
.catch(error => {
setTimeout(() => {
if (retries === 1) {
reject(error)
return
}
console.warn(`ChunkLoad failed. Will retry ${retries - 1} more times. Retrying...`)
// Passing on "reject" is the important part
retry(fn, {
retries: retries - 1,
interval: exponentialBackoff ? interval * 2 : interval
}).then(resolve, reject)
}, interval)
})
})
}
Than you can use it like this (with the default options):比你可以像这样使用它(使用默认选项):
loadable(() => retry(() => import(...)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.