Only Root Route is being rendered. IndexRoute Not

2019-05-26 21:20发布

问题:

I am building a simple blogging application and the App component (root path) is overriding the "posts/new" route, and IndexRoute is not rendering the posts_index component.

Basically, Only the App is rendering. Any feedback is welcome. See Below

// routes.js

import React from 'react';
import { Route, IndexRoute } from 'react-router';

import App from './components/app';
import PostsIndex from './components/posts_index';
import PostsNew from './components/posts_new';

export default (
    <Route path="/" component={App}>
      <IndexRoute component={PostsIndex}/>
      <Route path="posts/new" component={PostsNew}/>
    </Route>
);

// app.js

import React from 'react';
import { Component } from 'react';

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

// posts_new.js

import React, { Component } from 'react';

class PostsNew extends Component {
  render() {
    return (
      <div>Create Posts</div>
    );
  }
}

export default PostsNew;

// posts_index.js

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPosts } from '../actions/index';

class PostsIndex extends Component {
  componentWillMount() {
    this.props.fetchPosts();
  }

  render() {
  return (
    <div>List of Blog Posts</div>
    );
  }
};

export default connect(null, { fetchPosts })(PostsIndex);

回答1:

react-router will pass the nested routes down as children, so in your App component, you need to render this.props.children.

I.e. change your App component to this:

export default class App extends Component {
  render() {
    return (
      <div>React simple starter</div>
      { this.props.children }
    );
  }
}

And you should see the PostsIndex component when opening /, and PostsNew when opening /posts/new!


See the official react-router docs for more information