1

我正在尝试将代码拆分应用于我的 React 应用程序。下面的代码是我的路线,由Loadablefrom应用了代码拆分react-loadable。通过实现,每次我访问每个页面时,都会正确加载来自 webpack 的代码块。但是,当我最初访问我的网页时,它最初会导致屏幕闪烁。之后,如果我移动到另一个页面,屏幕不再闪烁。仅在最初访问我的网站时才会发生。

有谁知道为什么会这样?我的配置有问题吗?

顺便说一句,我在我的 React 应用程序中使用了 Node.js 的服务器端渲染。是否与代码拆分导致的屏幕闪烁有关?

路线.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);
}
4

1 回答 1

0

发生闪烁是因为路由器在路由时没有组件的来源,并且它按照您在提供给 Loadable HOCnull的 func 中定义的方式呈现,loading以防止闪烁您可以呈现一个看起来像这样的 Loading 组件:https:// github.com/osamu38/react-loadable-router-example/blob/master/src/components/Loading.js

或者您可以像这样预加载所有页面 onComponentDidMount (您应该将您的组件转换为类组件):

 componentDidMount = () => {
    About.preload()
    Landing.preload()
  }
于 2019-02-10T09:14:57.923 回答