我正在尝试在示例应用程序中设置 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 许可协议
我假设您使用的是 React-Router V4,就像您在原始 Sandbox Link 中使用的一样。
You are rendering the
Main
component in the call toReactDOM.render
that renders aLink
and Main component is outside ofRouter
, that’s why it正在抛出错误:变化:
使用 这些 Routers 、 BrowserRouter/HashRouter 等中的任何一个,因为您使用的是 React-Router V4。
路由器只能有一个孩子,因此将所有路由包装在
div
或 Switch 中。React-Router V4 没有嵌套路由的概念,如果您想使用嵌套路由,则直接在该组件内定义这些路由。
使用这些更改中的每一个检查 此工作示例。
父组件:
Main
来自路由的组件等等。
还要检查这个答案: Nested routes with react router v4