简体   繁体   中英

React-router cannot find components of other pages in the app

I am trying to set up a test component, which is basically a navigation bar and two components to navigate around. This is what it looks like:

class Page1 extends Component{
  render(){
    return (<div>Page1</div>);
  }
}

class Page2 extends Component{
  render(){
    return (<div>Page222</div>);
  }
}

class App extends Component{
  render(){
        console.log('children: ', this.props.children);
    return(
      <div>
        <NavigationBar/>

        {this.props.children}
      </div>

    );
  }
}

ReactDOM.render(
  <Router history={browserHistory}>
    <Route component={App} >
      <Route path="/" component={App}/>
      <Route path="page1" component={Page1}/>
      <Route path="page2" component={Page2}/>
    </Route>
</Router>,
    document.getElementById("app")
); 

The navigation bar is just a generic bootstrap navbar which is appearing fine. The problem I am having is when I navigate (or click on the Page1 or Page2 buttons), I get the message:

Cannot GET /page1

Even though the components and the routing is all set up and linking itself also seems to be fine.

I should also mention that the this.props.children is also null.

Any ideas on what I am doing wrong?

Add path="/" to the main App Route. Also, you are rendering the App component twice within your configuration. Which won't work properly. You should change it to:

class Page1 extends Component{
  render(){
    return (<div>Page1</div>);
  }
}

class Page2 extends Component{
  render(){
    return (<div>Page222</div>);
  }
}

class Home extends Component {
    render(){
      return(<h1>I AM HOME</h1>);
    }
}

class App extends Component{
  render(){
    console.log('children: ', this.props.children);
    return(
      <div>
        <NavigationBar/>

        {this.props.children}
      </div>
    );
  }
}

ReactDOM.render(
    <Router history={browserHistory}>
      <Route path="/" component={App} >
        <IndexRoute component={Home} /> //Being a different component
        <Route path="page1" component={Page1}/>
        <Route path="page2" component={Page2}/>
      </Route>
    </Router>,
    document.getElementById("app")
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM