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>

    );
   }

}
凯尔·卡里卡·圣

发现了!

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

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章