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

React Router v4 Nested Routes pass in match with Class Component

我正在尝试在我的应用程序中使用嵌套路由。使用 class 语法声明组件的地方。

如何通过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>

    );
   }

}

找到了!

如果您在下面的渲染中查看,它被保存为 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>
    );
   }

}