每当您尝试Link
在 之外的页面上显示 a时,BrowserRouter
您都会收到该错误。
此错误消息实质上是说任何不是我们的子组件的组件<Router>
都不能包含任何与 React Router 相关的组件。
您需要将您的组件层次结构迁移到您在上面第一个答案中看到的样子。对于可能需要查看更多示例的其他任何人查看这篇文章。
假设您有一个如下所示的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;
您的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;
请注意,Header.js
组件正在使用Link
标签 fromreact-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;
请仔细检查并确保您<Header />
的组件不仅在<BrowserRouter>
内,而且在 内<div>
,否则您还会收到错误,即路由器可能只有一个子项,<div>
该子项指的是 的子项<BrowserRouter>
. 其他所有东西,比如Route
和 组件,都必须在层次结构中。
所以现在<Header />
是标签<BrowserRouter>
内的子<div>
元素,它可以成功地使用Link
元素。