我正在尝试将代码拆分应用于我的React应用。以下代码是我的路线,其中Loadable
和react-loadable
应用了代码拆分。通过该实现,每次我访问每个页面时,都会正确加载来自webpack的代码块。但是,当我最初访问网页时,最初会导致屏幕闪烁。之后,如果我移至另一页,则不再有屏幕闪烁。仅在最初访问我的网站时发生。
有人知道为什么会这样吗?我的配置有问题吗?
顺便说一句,我在React应用程序中使用了Node.js进行服务器端渲染。是否与代码拆分引起的屏幕闪烁有关?
routes.jsx
import React from "react";
import Loadable from "react-loadable";
import { Route, Switch } from "react-router-dom";
import NotFound from "routes/not-found";
const Landing = Loadable({
loader: () => import(/* webpackChunkName: "landing" */ "routes/landing"),
loading: () => null,
modules: ["landing"]
});
const About = Loadable({
loader: () => import(/* webpackChunkName: "about" */ "routes/about"),
loading: () => null,
modules: ["about"]
});
export default props => {
return (
<Switch>
<Route
exact
path="/"
render={routeProps => <Landing {...routeProps} options={options} />}
/>
{/* <Route exact path="/" component={Homepage} /> */}
<Route
exact
path="/about"
render={routeProps => <About {...routeProps} options={options} />}
/>
<Route component={NotFound} />
</Switch>
);
};
src / index.js
const { store, history } = createStore();
const generateClassName = createGenerateClassName();
const Application = (
<JssProvider generateClassName={generateClassName}>
<MuiThemeProvider theme={theme}>
<Provider store={store}>
<ConnectedRouter history={history}>
<Frontload noServerRender={true}>
<App />
</Frontload>
</ConnectedRouter>
</Provider>
</MuiThemeProvider>
</JssProvider>
);
const root = document.querySelector("#root");
if (root.hasChildNodes() === true) {
// If it's an SSR, we use hydrate to get fast page loads by just
// attaching event listeners after the initial render
Loadable.preloadReady().then(() => {
hydrate(Application, root, () => {
document.getElementById("jss-styles").remove();
});
});
} else {
// If we're not running on the server, just render like normal
render(Application, root);
}
答案 0 :(得分:0)
之所以会发生闪烁,是因为路由器在路由时没有组件的来源,并且会根据提供给Loadable HOC的null
函数中的定义呈现loading
为防止闪烁,您可以呈现一个看起来像这样的Loading组件:https://github.com/osamu38/react-loadable-router-example/blob/master/src/components/Loading.js
或者您可以像这样预加载ComponentDidMount上的所有页面(您应该将其转换为类组件):
componentDidMount = () => {
About.preload()
Landing.preload()
}