reactjs 你不应该在 <Router> 之外使用 <Link>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48640280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
You should not use <Link> outside a <Router>
提问by A7DC
I'm trying to set up react-router in an example application, and I'm getting the following error:
我正在尝试在示例应用程序中设置 react-router,但出现以下错误:
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/Maincomponent
子/Main组件
export default () => (
<div>
<h1>
<Link to="/">Redux example</Link>
</h1>
</div>
)
Any idea what I'm doing wrong here?
知道我在这里做错了什么吗?
Here's a Sandbox linkto demonstrate the problem.
这是一个 Sandbox 链接来演示这个问题。
采纳答案by Mayank Shukla
I'm assuming that you are using React-Router V4, as you used the same in the original Sandbox Link.
我假设您使用的是 React-Router V4,就像您在原始Sandbox Link 中使用的一样。
You are rendering the Maincomponent in the call to ReactDOM.renderthat renders a Linkand Main component is outside of Router, that's why it is throwing the error:
您正在Main调用ReactDOM.render渲染 aLink并且 Main 组件在 之外的组件Router,这就是它抛出错误的原因:
You should not use <Link> outside a <Router>
你不应该在 <Router> 之外使用 <Link>
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
divor 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.
使用这些 Routers、 BrowserRouter/HashRouter 等中的任何一种...,因为您使用的是 React-Router V4。
路由器只能有一个子节点,因此将所有路由都包装在 a
div或Switch 中。React-Router V4 没有嵌套路由的概念,如果你想使用嵌套路由,那么直接在该组件内部定义这些路由。
Check this working examplewith 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'));
Maincomponent from route
Main来自路由的组件
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
还要检查这个答案:Nested routes with react router v4
回答by MBehtemam
For JESTusers
对于JEST用户
if you use Jest for testing and this error happen just wrap your component with <BrowserRouter>
如果您使用 Jest 进行测试并且发生此错误,只需将您的组件与 <BrowserRouter>
describe('Test suits for MyComponentWithLink', () => {
it('should match with snapshot', () => {
const tree = renderer
.create(
<BrowserRouter>
<MyComponentWithLink/>
</BrowserRouter>
)
.toJSON();
expect(tree).toMatchSnapshot();
});
});
回答by Basavaraj Hadimani
Enclose Link component inside BrowserRouter component
将 Link 组件包含在 BrowserRouter 组件中
export default () => (
<div>
<h1>
<BrowserRouter>
<Link to="/">Redux example</Link>
</BrowserRouter>
</h1>
</div>
)
回答by Daniel
Whenever you try to show a Linkon a page thats outside the BrowserRouteryou will get that error.
每当您尝试Link在 之外的页面上显示 a时,BrowserRouter您都会收到该错误。
This error message is essentially saying that any component that is not a child of our <Router>cannot contain any React Router related components.
此错误消息本质上是说任何不是我们的子组件的组件<Router>都不能包含任何与 React Router 相关的组件。
You need to migrate your component hierarchy to how you see it in the first answer above. For anyone else reviewing this post who may need to look at more examples.
您需要将您的组件层次结构迁移到您在上面第一个答案中看到的样子。对于可能需要查看更多示例的其他人查看此帖子。
Let's say you have a Header.jscomponent that looks like this:
假设您有一个如下所示的Header.js组件:
import React from 'react';
import { Link } from 'react-router-dom';
const Header = () => {
return (
<div className="ui secondary pointing menu">
<Link to="/" className="item">
Streamy
</Link>
<div className="right menu">
<Link to="/" className="item">
All Streams
</Link>
</div>
</div>
);
};
export default Header;
And your App.jsfile looks like this:
您的App.js文件如下所示:
import React from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom';
import StreamCreate from './streams/StreamCreate';
import StreamEdit from './streams/StreamEdit';
import StreamDelete from './streams/StreamDelete';
import StreamList from './streams/StreamList';
import StreamShow from './streams/StreamShow';
import Header from './Header';
const App = () => {
return (
<div className="ui container">
<Header />
<BrowserRouter>
<div>
<Route path="/" exact component={StreamList} />
<Route path="/streams/new" exact component={StreamCreate} />
<Route path="/streams/edit" exact component={StreamEdit} />
<Route path="/streams/delete" exact component={StreamDelete} />
<Route path="/streams/show" exact component={StreamShow} />
</div>
</BrowserRouter>
</div>
);
};
export default App;
Notice that the Header.jscomponent is making use of the Linktag from react-router-dombut the componet was placed outside the <BrowserRouter>, this will lead to the same error as the one experience by the OP. In this case, you can make the correction in one move:
请注意,该Header.js组件正在使用Linkfrom 标记,react-router-dom但该组件被放置在 之外<BrowserRouter>,这将导致与 OP 体验相同的错误。在这种情况下,您可以一步进行更正:
import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import StreamCreate from './streams/StreamCreate';
import StreamEdit from './streams/StreamEdit';
import StreamDelete from './streams/StreamDelete';
import StreamList from './streams/StreamList';
import StreamShow from './streams/StreamShow';
import Header from './Header';
const App = () => {
return (
<div className="ui container">
<BrowserRouter>
<div>
<Header />
<Route path="/" exact component={StreamList} />
<Route path="/streams/new" exact component={StreamCreate} />
<Route path="/streams/edit" exact component={StreamEdit} />
<Route path="/streams/delete" exact component={StreamDelete} />
<Route path="/streams/show" exact component={StreamShow} />
</div>
</BrowserRouter>
</div>
);
};
export default App;
Please review carefully and ensure you have the <Header />or whatever your component may be inside of not only the <BrowserRouter>but also inside of the <div>, otherwise you will also get the error that a Router may only have one child which is referring to the <div>which is the child of <BrowserRouter>. Everything else such as Routeand components must go within it in the hierarchy.
请仔细检查并确保您<Header />的组件不仅在<BrowserRouter>内,而且在 内<div>,否则您还会收到错误,即路由器可能只有一个子项,<div>该子项指的是 的子项<BrowserRouter>. 其他所有东西,比如Route和 组件,都必须在层次结构中。
So now the <Header />is a child of the <BrowserRouter>within the <div>tags and it can successfully make use of the Linkelement.
所以现在<Header />是标签<BrowserRouter>内的子<div>元素,它可以成功地使用Link元素。
回答by mj sameri
I kinda come up with this code :
我有点想出这个代码:
import React from 'react';
import { render } from 'react-dom';
// import componentns
import Main from './components/Main';
import PhotoGrid from './components/PhotoGrid';
import Single from './components/Single';
// import react router
import { Router, Route, IndexRoute, BrowserRouter, browserHistory} from 'react-router-dom'
class MainComponent extends React.Component {
render() {
return (
<div>
<BrowserRouter history={browserHistory}>
<Route path="/" component={Main} >
<IndexRoute component={PhotoGrid}></IndexRoute>
<Route path="/view/:postId" component={Single}></Route>
</Route>
</BrowserRouter>
</div>
);
}
}
render(<MainComponent />, document.getElementById('root'));
I think the error was because you were rendering the Maincomponent, and the Maincomponent didn't know anything about Router, so you have to render its father component.
我认为错误是因为您正在渲染Main组件,而Main组件对 一无所知Router,因此您必须渲染其父组件。
回答by Ivan Carrasco Quiroz
Make it simple:
让它变得简单:
render(<BrowserRouter><Main /></BrowserRouter>, document.getElementById('root'));
and don't forget: import { BrowserRouter } from "react-router-dom";
并且不要忘记: import { BrowserRouter } from "react-router-dom";
回答by vaskort
I was getting this error because I was importing a reusable component from an npm library and the versions of react-router-domdid not match.
我收到这个错误是因为我从 npm 库中导入了一个可重用的组件,并且版本react-router-dom不匹配。
So make sure you use the same version in both places!
所以请确保在两个地方使用相同的版本!
回答by Laveena
You can put the Link component inside the Router componet. Something like this:
您可以将 Link 组件放在 Router 组件中。像这样的东西:
<Router>
<Route path='/complete-profiles' component={Profiles} />
<Link to='/complete-profiles'>
<div>Completed Profiles</div>
</Link>
</Router>
回答by Prakhar Mittal
Write routerin place of Mainin render(last line in the code). Like this ReactDOM.render(router, document.getElementById('root'));
在渲染中编写路由器来代替Main(代码中的最后一行)。像这样 ReactDOM.render(router, document.getElementById('root'));
回答by PRADEEP YADAV
If you don't want to change much, use below code inside onClick()method.
如果您不想更改太多,请在 onClick() 方法中使用以下代码。
this.props.history.push('/');

