1

Github上的相关帖子

目前,我很难在我的 react-redux 应用程序中正确使用这两个库。

我的代码如下所示:

index.js

import { Provider } from 'react-redux';
import { ConnectedRouter } from 'connected-react-router';
...
ReactDOM.render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <App />
    </ConnectedRouter>
  </Provider>,
  rootElement
);

应用程序.js

...
export default () => (
  <Layout>
    <Switch>
      <Route exact path="/" component={Home} />
      <Route path="/test" component={Test} />
    </Switch>
  </Layout>
);

布局.js

...
export default function Layout(props) {
  return (
    <div class="ms-Fabric">
      <div class="ms-Grid-row">
        <div class="ms-Grid-col ms-lg2">
          <Navigation />
        </div>
        <div class="ms-Grid-col ms-lg10">{props.children}</div>
      </div>
    </div>
  );
}

导航.js

import React from 'react';
import { withRouter } from 'react-router-dom';
import { Nav } from 'office-ui-fabric-react';

export default withRouter(({ history }) => (
  <div className="ms-NavExample-LeftPane">
    <Nav
      onLinkClick={(event, element) => {
        event.preventDefault();
        history.push(element.url);
      }}
      groups={[
        {
          links: [
            {
              name: 'Home',
              url: '/',
              key: 'home'
            },
            {
              name: 'Test',
              url: '/Test',
              key: 'test'
            }
          ]
        }
      ]}
    />
  </div>
));

但是,当我运行应用程序时,它会显示You should not use <Route> outside a <Router>. 导航肯定在 中ConnectedRouter而且看起来这个路由器与react-routerv4 配合得很好,所以我不知道如何处理这个问题。

有人可以给我一个建议吗?

4

1 回答 1

0

您项目的架构:Provider > ConnectedRouter > App > Layout (have NavLink) > Switch > Routes

您必须以这种方式构建架构:Provider > ConnectedRouter > routes file > Switch > Routes > Layout in component

// index.js
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'connected-react-router';
import routes from 'routes/index';
import store from 'store/configureStore';

render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      {routes}
    </ConnectedRouter>
  </Provider>,
  document.getElementById('root'),
);

// routes.js
const routes = (
  <Switch>
    <Route exact path="/" component={Home} />
    <Route path="/test" component={Test} />
  </Switch>
);

export default routes;

于 2018-11-25T20:03:44.017 回答