React Router v4嵌套路由通过与类组件匹配

时间:2018-12-22 01:04:50

标签: javascript reactjs react-router react-router-v4

我正在尝试在应用程序中使用嵌套路由。使用类语法声明组件的位置。

如何通过match

如下所示,我正在使用componentDidMount()函数提取数据,因此我需要具有成员函数,并且希望该组件处理所有逻辑。

import React, { Component } from 'react';
import ListItem from './ListItem';
import Post from './Post';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

//holds the state for all the components
//passes into listing
//listing will re-direct to proper post using router

export default class Blog extends Component {

  constructor(props){
    super(props);

    this.state = {
      articles: [],
      content: null
    };
  }

  storeData = (data) => {
    const articles = data.map((post, index) => {
      return {
        key: index,
        title: post.title.rendered,
        content: post.content.rendered,
        excerpt: post.excerpt.rendered,
        slug: post.slug
      };
    });

    this.setState(
      {
        articles: articles
      }
    );
  };

  componentDidMount() {

    let articles = [];
    fetch('https://XXXXX.com/posts/')
      .then(data => data.json())
      .then(this.storeData).catch(err => console.log(err));

  }

  render(){

    return(
      <div className="blog">
          <h2> Listings </h2>
            { this.state.articles.map(post => (
              <Link to= { `path/${post.slug}` } >
                <ListItem
                  key={post.key}
                  title={post.title}
                  content={post.content}
                 />
               </Link>
            ))
          }
          <Route path='posts/:slug' component={Post} />
      </div>

    );
   }

}

1 个答案:

答案 0 :(得分:0)

找出答案!

如果您在渲染中查看下方,它将另存为this.props

但是,现在它呈现在下面的组件,而不是替换到另一个页面。

  render(){
    return(
      <div className="blog">
          <h2> Listings </h2>
            { this.state.articles.map(post => (
              <Link to={ `${this.props.match.url}/${post.slug}` } >
                <ListItem
                  key={post.key}
                  title={post.title}
                  content={post.content}
                 />
               </Link>
            ))
          }
          <Route path={ `${this.props.match.path}/:slug` } component={Post} />
      </div>
    );
   }

}