[英]React Router v4, “A router may have only one child element” using multiple routes
I'm trying to render a sidebar along with a main content area using react-router-dom
. 我正在尝试使用
react-router-dom
渲染侧边栏以及主要内容区域。 I could just render <Sidebar/>
normally but I want to pass it the location prop because of another error I was getting where clicking a <Link/>
in the sidebar would change the URL but wouldn't update the main content area. 我可以正常渲染
<Sidebar/>
但我想将其传递给位置道具,因为另一个错误是我发现单击侧边栏中的<Link/>
会更改URL,但不会更新主要内容区域。 So rendering the Sidebar
component using a route with no path I thought would always render the Sidebar
AND let me pass the location. 因此,我认为使用没有路径的路线来渲染
Sidebar
组件,我想总是会渲染Sidebar
并让我传递位置。 However I'm getting this error... 但是我收到此错误...
Invariant Violation: A
<Router>
may have only one child element不变违反:
<Router>
可能只有一个子元素
Here's my code in App.js 这是我在App.js中的代码
import React, { Component } from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.css'
import '../node_modules/bootstrap/dist/css/bootstrap-theme.css'
import Sidebar from './components/Sidebar/sidebar'
import SidebarContent from './components/Sidebar/sidebar_content'
import Blank from './components/Blank/blank';
import Course from './components/Course/course';
import { Grid, Col, Row } from '../node_modules/react-bootstrap'
import {
Route,
BrowserRouter as Router,
Switch,
withRouter,
Redirect,
Link
} from 'react-router-dom'
class App extends Component {
render() {
const sidebar = <SidebarContent params={this.props.params}/>
document.body.style.overflow = "hidden"
const sidebarProps = {
sidebar: sidebar,
docked: true,
shadow: false,
touchHandleWidth: 20,
dragToggleDistance: 30,
touch: false,
transitions: false,
pullRight: false,
open: true,
}
const CourseParent = (props) => {
return(<Course courseID={props.courseID}/>);
}
const SidebarParent = (props) => {
return(<Sidebar {...sidebarProps} className="Sidebar" location={props.location}/>);
}
return (
<Router>
<div>
<Grid fluid={true}>
<Row className="show-grid">
<Col className="col-md-2" style={{height: '100vh', width: '175px'}}>
{/* <Sidebar {...sidebarProps} className="Sidebar" location={location}/> */}
<div>
<Route render={({ location }) => (
<Sidebar {...sidebarProps} className="Sidebar" location={location}/>
)}/>
</div>
</Col>
<Col className="col-md-auto">
<Switch>
<Route exact path="/" component={Blank}/>
<Route path="/course/:courseID" component={CourseParent}/>
<Redirect to="/" />
</Switch>
</Col>
</Row>
</Grid>
</div>
</Router>
);
}
}
export default App;
There should be single in your whole app and it contain only a single component. 您的整个应用中应该只有一个组件,并且只包含一个组件。 You can find detail about this at here: https://medium.com/@pshrmn/a-simple-react-router-v4-tutorial-7f23ff27adf
您可以在此处找到有关此内容的详细信息: https : //medium.com/@pshrmn/a-simple-react-router-v4-tutorial-7f23ff27adf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.