Вложенные маршрутизаторы - реагирующий маршрутизатор и подключенный реагирующий маршрутизатор - PullRequest
0 голосов
/ 09 июня 2019

Я пытаюсь лениво загрузить определения маршрутов, поэтому предположим, что у меня есть родительское приложение:

const history = createBrowserHistory();
const store = createStore({ history });

const app = (
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <Switch>
        <Route exact path="/" render={() => 'home'} />

        /** Nested LazyLoad Sub Application Profile **/
        <Route path="/profile" component={LazyProfile} />
        /** / Profile **/

        <Route component={NotFound} />
      </Switch>
    </ConnectedRouter>
  </Provider>
);

LazyProfile - это реактивно загружаемый компонент, который лениво впрыскивает весь профиль:

// LazyProfile.jsx

export const LazyProfile = Loadable.Map({
  loader: {
    exports: () => import(/* webpackChunkName: 'profile' */ '@company/app-plugin-profile'),
  },
  loading: () => 'loading',
  render(result, props) {
    const { Component } = result.exports;

    return <Component />;
  },
});

и Profile - это компонент, который живет где-то еще и устанавливается через npm. Он также загружает все дочерние маршруты для области profile ...

// Profile.jsx

export const Profile = (props) => (
  <Fragment>
    <h1>Profile</h1>

    <Switch {...props}>
      <Route path="/profile/a" render={() => 'profile a'} />
      <Route path="/profile/b" render={() => 'profile b'} />
    </Switch>
  </Fragment>
);

Эта конфигурация приводит к следующей ошибке, которая мне кажется странной, поскольку компоненты Profile фактически монтируются как дочерние элементы маршрутизатора.

index.tsx:29 Uncaught Error: Invariant failed: You should not use <Switch> outside a <Router>
    at invariant (tiny-invariant.esm.js:11)
    at react-router.js:635
    at updateContextConsumer (react-dom.development.js:15484)
    at beginWork (react-dom.development.js:15672)
    at performUnitOfWork (react-dom.development.js:19312)
    at workLoop (react-dom.development.js:19352)
    at HTMLUnknownElement.callCallback (react-dom.development.js:149)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:199)
    at invokeGuardedCallback (react-dom.development.js:256)
    at replayUnitOfWork (react-dom.development.js:18578)
invariant @ tiny-invariant.esm.js:11
(anonymous) @ react-router.js:635
updateContextConsumer @ react-dom.development.js:15484
beginWork @ react-dom.development.js:15672
performUnitOfWork @ react-dom.development.js:19312
workLoop @ react-dom.development.js:19352
callCallback @ react-dom.development.js:149
invokeGuardedCallbackDev @ react-dom.development.js:199
invokeGuardedCallback @ react-dom.development.js:256
replayUnitOfWork @ react-dom.development.js:18578
renderRoot @ react-dom.development.js:19468
performWorkOnRoot @ react-dom.development.js:20342
performWork @ react-dom.development.js:20254
performSyncWork @ react-dom.development.js:20228
requestWork @ react-dom.development.js:20097
scheduleWork @ react-dom.development.js:19911
enqueueSetState @ react-dom.development.js:11169
../../../../node_modules/react/cjs/react.development.js.Component.setState @ react.development.js:335
update @ index.js:205
(anonymous) @ index.js:215
Promise.then (async)
_loadModule @ index.js:214
componentWillMount @ index.js:168
callComponentWillMount @ react-dom.development.js:11421
mountClassInstance @ react-dom.development.js:11514
updateClassComponent @ react-dom.development.js:14688
beginWork @ react-dom.development.js:15644
performUnitOfWork @ react-dom.development.js:19312
workLoop @ react-dom.development.js:19352
renderRoot @ react-dom.development.js:19435
performWorkOnRoot @ react-dom.development.js:20342
performWork @ react-dom.development.js:20254
performSyncWork @ react-dom.development.js:20228
requestWork @ react-dom.development.js:20097
scheduleWork @ react-dom.development.js:19911
scheduleRootUpdate @ react-dom.development.js:20572
updateContainerAtExpirationTime @ react-dom.development.js:20600
updateContainer @ react-dom.development.js:20657
../../../../node_modules/react-dom/cjs/react-dom.development.js.ReactRoot.render @ react-dom.development.js:20953
(anonymous) @ react-dom.development.js:21090
unbatchedUpdates @ react-dom.development.js:20459
legacyRenderSubtreeIntoContainer @ react-dom.development.js:21086
render @ react-dom.development.js:21155
_callee$ @ index.tsx:29
tryCatch @ runtime.js:45
invoke @ runtime.js:271
prototype.<computed> @ runtime.js:97
asyncGeneratorStep @ asyncToGenerator.js:3
_next @ asyncToGenerator.js:25
Promise.then (async)
asyncGeneratorStep @ asyncToGenerator.js:13
_next @ asyncToGenerator.js:25
Promise.then (async)
asyncGeneratorStep @ asyncToGenerator.js:13
_next @ asyncToGenerator.js:25
(anonymous) @ asyncToGenerator.js:32
(anonymous) @ asyncToGenerator.js:21
./index.tsx @ index.tsx:11
__webpack_require__ @ bootstrap:63
0 @ application.js:77532
__webpack_require__ @ bootstrap:63
(anonymous) @ bootstrap:197
(anonymous) @ bootstrap:197
index.tsx:29 The above error occurred in the <Context.Consumer> component:
    in Switch (created by Component)
    in Component (created by LoadableComponent)
    in LoadableComponent (created by Context.Consumer)
    in Route (created by Routes)
    in Switch (created by Routes)
    in Routes
    in Router (created by ConnectedRouter)
    in ConnectedRouter (created by Context.Consumer)
    in ConnectedRouterWithContext (created by ConnectFunction)
    in ConnectFunction
    in Provider
    in ApolloProvider

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://react-error-boundaries to learn more about error boundaries.
logCapturedError @ react-dom.development.js:17117
logError @ react-dom.development.js:17153
update.callback @ react-dom.development.js:18065
callCallback @ react-dom.development.js:16433
commitUpdateEffects @ react-dom.development.js:16472
commitUpdateQueue @ react-dom.development.js:16463
commitLifeCycles @ react-dom.development.js:17383
commitAllLifeCycles @ react-dom.development.js:18736
callCallback @ react-dom.development.js:149
invokeGuardedCallbackDev @ react-dom.development.js:199
invokeGuardedCallback @ react-dom.development.js:256
commitRoot @ react-dom.development.js:18948
(anonymous) @ react-dom.development.js:20418
unstable_runWithPriority @ scheduler.development.js:255
completeRoot @ react-dom.development.js:20417
performWorkOnRoot @ react-dom.development.js:20346
performWork @ react-dom.development.js:20254
performSyncWork @ react-dom.development.js:20228
requestWork @ react-dom.development.js:20097
scheduleWork @ react-dom.development.js:19911
enqueueSetState @ react-dom.development.js:11169
../../../../node_modules/react/cjs/react.development.js.Component.setState @ react.development.js:335
update @ index.js:205
(anonymous) @ index.js:215
Promise.then (async)
_loadModule @ index.js:214
componentWillMount @ index.js:168
callComponentWillMount @ react-dom.development.js:11421
mountClassInstance @ react-dom.development.js:11514
updateClassComponent @ react-dom.development.js:14688
beginWork @ react-dom.development.js:15644
performUnitOfWork @ react-dom.development.js:19312
workLoop @ react-dom.development.js:19352
renderRoot @ react-dom.development.js:19435
performWorkOnRoot @ react-dom.development.js:20342
performWork @ react-dom.development.js:20254
performSyncWork @ react-dom.development.js:20228
requestWork @ react-dom.development.js:20097
scheduleWork @ react-dom.development.js:19911
scheduleRootUpdate @ react-dom.development.js:20572
updateContainerAtExpirationTime @ react-dom.development.js:20600
updateContainer @ react-dom.development.js:20657
../../../../node_modules/react-dom/cjs/react-dom.development.js.ReactRoot.render @ react-dom.development.js:20953
(anonymous) @ react-dom.development.js:21090
unbatchedUpdates @ react-dom.development.js:20459
legacyRenderSubtreeIntoContainer @ react-dom.development.js:21086
render @ react-dom.development.js:21155
_callee$ @ index.tsx:29
tryCatch @ runtime.js:45
invoke @ runtime.js:271
prototype.<computed> @ runtime.js:97
asyncGeneratorStep @ asyncToGenerator.js:3
_next @ asyncToGenerator.js:25
Promise.then (async)
asyncGeneratorStep @ asyncToGenerator.js:13
_next @ asyncToGenerator.js:25
Promise.then (async)
asyncGeneratorStep @ asyncToGenerator.js:13
_next @ asyncToGenerator.js:25
(anonymous) @ asyncToGenerator.js:32
(anonymous) @ asyncToGenerator.js:21
./index.tsx @ index.tsx:11
__webpack_require__ @ bootstrap:63
0 @ application.js:77532
__webpack_require__ @ bootstrap:63
(anonymous) @ bootstrap:197
(anonymous) @ bootstrap:197

и все работает отлично, если я включу BrowserRouter в определение профиля:

export const Profile = (props) => (
  <BrowserRouter {...props}>
    <Fragment>
      <h1>Profile</h1>

      <Switch {...props}>
        <Route path="/profile/a" render={() => 'profile a'} />
        <Route path="/profile/b" render={() => 'profile b'} />
      </Switch>
    </Fragment>
  </BrowserRouter>
);

Я доволен этим, но мне интересно, может ли вложение two routers привести к нежелательным эффектам ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...