你不应该使用 <Link>在<Router>之外 [英] You should not use <Link> outside a <Router>
问题描述
I'm trying to set up react-router in an example application, and I'm getting the following error:
You should not use <Link> outside a <Router>
My app is set up like so:
Parent component
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'));
Child/Main
component
export default () => (
<div>
<h1>
<Link to="/">Redux example</Link>
</h1>
</div>
)
Any idea what I'm doing wrong here?
Here's a Sandbox link to demonstrate the problem.
I'm assuming that you are using React-Router V4, as you used the same in the original 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 is throwing the error:
You should not use <Link> outside a <Router>
Changes:
Use any one of these Routers, BrowserRouter/HashRouter etc..., because you are using React-Router V4.
Router can have only one child, so wrap all the routes in a
div
or Switch.React-Router V4, doesn't have the concept of nested routes, if you wants to use nested routes then define those routes directly inside that component.
Check this working example with each of these changes.
Parent Component:
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
component from route
import React from 'react';
import { Link } from 'react-router-dom';
export default () => (
<div>
<h1>
<Link to="/">Redux example</Link>
</h1>
</div>
)
Etc.
Also check this answer: Nested routes with react router v4
这篇关于你不应该使用 <Link>在<Router>之外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!