0

在我的项目中,我曾经依赖 react-loadable 来做一些代码拆分,与 react-router 一起延迟加载。就像是:

<Route component={component} />

Component = Loadable({
    loader: () => import(/* webpackChunkName: "Analyze" */ "./components/Analyze"),
})

分析组件实现componentDidMount和使用路由器的history.push状态变化。当一个新的 url 被推送并改变了一些参数,但仍然导致这个相同的“分析”组件时,只有componentDidUpdate被调用。我更新了这段代码以使用 React.lazy:

<Route component={(_props: any) =>
          <LazyComponentWrapper>
              <Component {..._props} />
          </LazyComponentWrapper>
        } />

Component = React.lazy(() => import(/* webpackChunkName: "Analyze" */ "./components/Analyze")),

function LazyComponentWrapper({ children }) {
  return (
    <Suspense fallback={<div>{LOADING}</div>}>
        {children}
    </Suspense>
  );

但是现在componentDidMound每次都意外调用。我不清楚这与反应路由器有关React.lazy还是与反应路由器有关。有什么线索吗?

4

1 回答 1

0

根据文档,将 Suspense 从 Route 组件中移出可能会更好,试试这个:

import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

const Home = lazy(() => import('./routes/Home'));
const Component = React.lazy(() => import(/* webpackChunkName: "Analyze" */ "./components/Analyze"))

const App = () => (
  <Router>
    <Suspense fallback={<div>Loading...</div>}>
      <Switch>
        <Route exact path="/" component={Home}/>
        <Route path="/analyze" component={Component}/>
      </Switch>
    </Suspense>
  </Router>
);
于 2020-03-27T15:55:52.540 回答