【问题标题】:React Router v4, "A router may have only one child element" using multiple routesReact Router v4,“一个路由器可能只有一个子元素”使用多个路由
【发布时间】:2018-03-17 19:18:49
【问题描述】:

我正在尝试使用react-router-dom 呈现边栏和主要内容区域。我可以正常渲染<Sidebar/>,但我想将位置属性传递给它,因为我遇到了另一个错误,点击侧边栏中的<Link/> 会更改URL,但不会更新主要内容区域。因此,使用没有路径的路径渲染Sidebar 组件我认为总是会渲染Sidebar 并让我通过该位置。但是我收到此错误...

不变违规:<Router> 可能只有一个子元素

这是我在 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;

【问题讨论】:

  • 这个路由器只有一个子元素。您确定这是导致错误的文件吗?你在其他地方使用路由器吗?
  • 你的Sidebar 组件是什么样子的
  • 就是这样!我在测试时忘记在我的Sidebar 组件中删除另一个&lt;Router/&gt;...谢谢!

标签: javascript reactjs react-router react-router-v4 react-router-dom


【解决方案1】:

您的整个应用程序中应该只有一个,并且它只包含一个组件。 您可以在此处找到有关此内容的详细信息: https://medium.com/@pshrmn/a-simple-react-router-v4-tutorial-7f23ff27adf

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-18
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    相关资源
    最近更新 更多