React Router only recognises index route

后端 未结 2 894
感情败类
感情败类 2021-01-07 04:19

I have 2 routes, / and /about and i\'ve tested with several more. All routes only render the home component which is /.

When

相关标签:
2条回答
  • 2021-01-07 04:49

    Since you've nested About under Home you need to render a <RouteHandler /> component within your Home component in order for React Router to be able to display your route components.

    import {RouteHandler} from 'react-router';
    
    var Home = React.createClass({
        render() {
            return (<div> this is the main component
                <RouteHandler />
            </div>);
        }
    });
    
    0 讨论(0)
  • 2021-01-07 05:03

    Using ES6 and the newest react-router would look like this:

    import React from 'react';
    import {
      Router,
      Route,
      IndexRoute,
    }
    from 'react-router';
    
    const routes = (
      <Router>
        <Route component={Home} path="/">
          <IndexRoute component={About}/>
        </Route>
      </Router>
    );
    
    const Home = React.createClass({
      render() {
        return (
          <div> this is the main component
            {this.props.children}
          </div>
        );
      }
    });
    
    //Remember to have your about component either imported or
    //defined somewhere
    
    React.render(routes, document.body);
    

    On a side note, if you want to match unfound route to a specific view, use this:

    <Route component={NotFound} path="*"></Route>
    

    Notice the path is set to *

    Also write your own NotFound component.

    Mine looks like this:

    const NotFound = React.createClass({
      render(){
       let _location = window.location.href;
        return(
          <div className="notfound-card">
            <div className="content">
              <a className="header">404 Invalid URL</a >
            </div>
            <hr></hr>
            <div className="description">
              <p>
                  You have reached:
              </p>
              <p className="location">
                {_location}
              </p>
            </div>
          </div>
        );
      }
    });
    
    0 讨论(0)
提交回复
热议问题