从 react-loadable 移动到 react.lazy 后意外调用 componentDidMount

componentDidMount unexpectedly called after move from react-loadable to react.lazy

在我的项目中,我曾经依赖react-loadable来做一些代码拆分,延迟加载和react-router。类似于:

<Route component={component} />

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

Analyze 组件实现 componentDidMount 并在状态更改时使用路由器的 history.push。当一个新的 url 被推送并改变了一些参数,但仍然导致相同的 "Analyze" 组件时,只有 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 或 react-router 有关。有什么线索吗?

根据 docs 将 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>
);