仅渲染根路由.IndexRoute 不渲染组件 [英] Only Root Route is being rendered. IndexRoute Not Rendering Components

查看:49
本文介绍了仅渲染根路由.IndexRoute 不渲染组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

// posts_new.js

import React, { Component } from 'react';

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

export default PostsNew;

//posts_index.js

// 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);

推荐答案

react-router 会将嵌套路由作为子级向下传递,因此在您的 App 组件中,您需要渲染 this.props.children.

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

即将您的 App 组件更改为:

I.e. change your App component to this:

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

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

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

查看官方 react-router 文档 了解更多信息

See the official react-router docs for more information

这篇关于仅渲染根路由.IndexRoute 不渲染组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆