仅渲染根路径。 IndexRoute不渲染组件

时间:2016-03-01 16:08:02

标签: reactjs react-router redux

我正在构建一个简单的博客应用程序,而App组件(根路径)正在覆盖“posts / new”路由,而IndexRoute不会呈现posts_index组件。

基本上,只有应用程序正在渲染。欢迎任何反馈。见下文

// 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 个答案:

答案 0 :(得分:4)

react-router将作为子项向下传递嵌套路由,因此在App组件中,您需要呈现this.props.children

即。将您的App组件更改为:

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

您应该在打开PostsIndex时看到/组件,在打开PostsNew时看到/posts/new

有关详细信息,请参阅官方react-router docs