React-router-dom-相同的路由问题

时间:2018-08-08 11:27:45

标签: reactjs react-router-dom

我是react js框架的新手,目前正在做导航,但是我遇到了有关路线的问题。这是我新安装的react js的组件。

Index.js

 import React from 'react';
 import ReactDOM from 'react-dom';
 import App from './App';
 import registerServiceWorker from './registerServiceWorker';
 import 'bootstrap/dist/css/bootstrap.min.css';


ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

App.js

import React, { Component } from 'react';
import './App.css';
import Routes from './routes';

class App extends Component {
  render() {
    return (
      <div>
        <Routes/>
      </div>
    );
  }
}
export default App;

src / routes / index.js

import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

import Root from '../components/Root';
import Home from '../components/Home';
import About from '../components/About';
import Contact from '../components/Contact';

export default() =>(
<BrowserRouter>
    <Switch>
        <Route exact path="/" component={Root}>
            <Route exact path="/home" component={Home}/>
            <Route exact path="/about" component={About}/>
            <Route exact path="/contact" component={Contact}/>
        </Route>
    </Switch>
</BrowserRouter>
)

src / components / Root.js

import React, { Component } from 'react';

import Header from './Header';

class Root extends Component {
  render() {
    console.log(this.props)
    return (
        <div>
            <div>
                <Header/>
            </div>
            <div>
                {this.props.children}
            </div>
        </div>
    );
  }
}
export default Root;

src / components / Header.js

import React, { Component } from 'react';
import {Navbar} from 'reactstrap';

class Header extends Component {

  render() {
    return (
        <div>
            <Navbar color="light" light expand="md">
                //navbar html code here
            </Navbar>
        </div>  
    );
  }
}
export default Header;

index.js:2178警告:您不应在同一路径中使用<Route component><Route children><Route children>将被忽略

这是我的问题。

2 个答案:

答案 0 :(得分:1)

我认为您的警告缺少一些信息,因为SO似乎已删除了XML之类的标记。

尽管看代码,我很确定警告应该说:

You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored

问题是您已将某些路线作为另一条路线的“子项”。您不需要这样做。

<Switch>
    <Route exact path="/" component={Root}>
        <Route exact path="/home" component={Home}/>
        <Route exact path="/about" component={About}/>
        <Route exact path="/contact" component={Contact}/>
    </Route> // This is the problem, you don't need to enclose this.
</Switch>

您无需将Route括起来,因为它们都是精确的,并且始终将组件与路径匹配。

<Switch>
    <Route exact path="/" component={Root} />
    <Route exact path="/home" component={Home}/>
    <Route exact path="/about" component={About}/>
    <Route exact path="/contact" component={Contact}/>
</Switch>

答案 1 :(得分:0)

  

这始终对我有用

     

Nested Routes in React Router v4