你不应该在 <Router> 之外使用 <Link>

新手上路,请多包涵

我正在尝试在示例应用程序中设置 react-router,但出现以下错误:

 You should not use <Link> outside a <Router>

我的应用程序设置如下:

父组件

const router = (
  <div className="sans-serif">
    <Router histpry={browserHistory}>
      <Route path="/" component={Main}>
        <IndexRoute component={PhotoGrid}></IndexRoute>
        <Route path="/view/:postId" component={Single}></Route>
      </Route>
    </Router>
  </div>
);

render(<Main />, document.getElementById('root'));

子/ Main 组件

export default () => (
  <div>
    <h1>
      <Link to="/">Redux example</Link>
    </h1>
  </div>
)

知道我在这里做错了什么吗?

这是一个沙盒链接 来演示该问题。

原文由 A7DC 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
2 个回答

我假设您使用的是 React-Router V4,就像您在原始 Sandbox Link 中使用的一样。

You are rendering the Main component in the call to ReactDOM.render that renders a Link and Main component is outside of Router , that’s why it正在抛出错误:

你不应该在 之外使用

变化

  1. 使用 这些 Routers 、 BrowserRouter/HashRouter 等中的任何一个,因为您使用的是 React-Router V4。

  2. 路由器只能有一个孩子,因此将所有路由包装在 divSwitch 中。

  3. React-Router V4 没有嵌套路由的概念,如果您想使用嵌套路由,则直接在该组件内定义这些路由。


使用这些更改中的每一个检查 此工作示例

父组件:

 const App = () => (
  <BrowserRouter>
    <div className="sans-serif">
      <Route path="/" component={Main} />
      <Route path="/view/:postId" component={Single} />
    </div>
  </BrowserRouter>
);

render(<App />, document.getElementById('root'));

Main 来自路由的组件

import React from 'react';
import { Link } from 'react-router-dom';

export default () => (
  <div>
    <h1>
      <Link to="/">Redux example</Link>
    </h1>
  </div>
)

等等。


还要检查这个答案: Nested routes with react router v4

原文由 Mayank Shukla 发布,翻译遵循 CC BY-SA 4.0 许可协议

对于 JEST 用户

如果您使用 Jest 进行测试并且发生此错误,只需将您的组件包装为 <BrowserRouter>

 describe('Test suits for MyComponentWithLink', () => {
it('should match with snapshot', () => {
const tree = renderer
  .create(
    <BrowserRouter>
      <MyComponentWithLink/>
    </BrowserRouter>
  )
  .toJSON();
 expect(tree).toMatchSnapshot();
 });
});

原文由 MBehtemam 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进