Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
251 views
in Technique[技术] by (71.8m points)

reactjs - Nesting Routes in react-router v4

I've upgraded the react router to version 4 in my application. But now I'm getting the error

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

What is wrong with this routing?

import {
    Switch,
    BrowserRouter as Router,
    Route, IndexRoute, Redirect,
    browserHistory
} from 'react-router-dom'   

render((
    <Router history={ browserHistory }>
        <Switch>
            <Route path='/' component={ Main }>
                <IndexRoute component={ Search } />
                <Route path='cars/:id' component={ Cars } />
                <Route path='vegetables/:id' component={ Vegetables } />
            </Route>
            <Redirect from='*' to='/' />
        </Switch>
    </Router>
), document.getElementById('main'))
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

IndexRoute and browserHistory are not available in the latest version, also Routes do not accept children Routes with v4, Instead, you can specify Routes within the component Itself

import {
    Switch,
    BrowserRouter as Router,
    Route,  Redirect
} from 'react-router-dom'   

render((
    <Router>
        <Switch>
            <Route exact path='/' component={ Main }/>

            <Redirect from='*' to='/' />
        </Switch>
    </Router>
), document.getElementById('main'))

Then in the Main Component

render() {
     const {match} = this.props;
     return (
        <div>
           {/* other things*/}
           <Route exact path="/" component={ Search } />
           <Route path={`${match.path}cars/:id`} component={ Cars } />
         </div>
    )

}

Similarly in the cars component

you will have

render() {
     const {match} = this.props;
     return (
        <div>
           {/* other things*/}
           <Route path={`${match.path}/vegetables/:id`} component={ Vegetables } />
        </div>
    )

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...