仅呈现根路由。IndexRoute 不渲染组件

IT技术 reactjs react-router redux
2021-05-16 03:10:28

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

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

// 路由.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>
    );
  }
}

// post_new.js

import React, { Component } from 'react';

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

export default PostsNew;

// post_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 会将嵌套的路由作为子项向下传递,因此在您的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 文档