使用React,Blog Posts和Wordpress API进行动态路由

时间:2018-01-26 10:45:30

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

我尝试按照this tutorial来了解动态路由的工作原理。现在,我想使用WordPress的API为每个帖子生成唯一的链接,而不是使用静态数据。我能够生成链接,但新页面上没有生成任何数据。我在这里做错了什么?

Articles.js(用作获取所有博客帖子的预览页面,按预期工作)

let sequence = (start...end).map(fibonacciFast)

Article.js(为了呈现每篇文章)

import React, { Component } from 'react';
import { Link, Route } from 'react-router-dom';
import Article from './Article';

const newsURL = "http://myprivateblogapi.com/wp-json/wp/v2/posts?_embed";

export default class Articles extends Component {   
 constructor(props) {
    super(props);
    this.state = {
      newsData: [],
      requestFailed: false
    }   }

  componentDidMount() {
    fetch(newsURL)
      .then(response => {
        if(!response.ok) {
          throw Error("Network request failed.");
        }
        return response
      })
      .then(d => d.json())
      .then(d => {
        this.setState({
          newsData: d
        })
      }, () => {
        this.setState({
          requestFailed: true
        })
      })   }

  render() {

    let articles = this.state.newsData.map((article, index) => {
      if(this.state.requestFailed) return <p>Failed!</p>
      if(!this.state.newsData) return <p>Loading...</p> 
      return(
        <div key={index} className="article-container">
          <div className="article-preview">
          <span className="article-date">{article.date}</span>
          <h5>{article.title.rendered}</h5>
          <div dangerouslySetInnerHTML={{ __html: article.excerpt.rendered }} />

          <Link to={`/news/${article.slug}`}>Read More...</Link>

          </div>
          <Route path={`/news/:articleSlug`}
          render={ (props) => <Article data={articles} {...props} />} />
        </div>

      )
    });

    return (
      <div>
        <h3>All Articles from Blog</h3>
        {articles}
      </div>
    )   } }

1 个答案:

答案 0 :(得分:1)

我认为问题在这里:

render={ (props) => <Article data={articles} {...props} />} />

在文章中你存储了地图的结果,所以它没有你期望的数据:

let articles = this.state.newsData.map(....)

解决方案

1 - 如果你想传递完整数组,那么就这样写(不是一个好主意):

render={ props => <Article data={this.state.newsData} {...props} />} />

2 - 传递单个对象,文章组件中不需要循环:

render={ props => <Article data={article} {...props} />} />

Article组件:

const Article = ({match, data}) => {
  let articleData;

  if(data)
    articleData = <div>
      <h3> {article.title.rendered}</h3>
      <p>{article.content.rendered}</p>
      <hr />
    </div>

  else 
    articleData = <h2> Sorry. That article doesn't exist. </h2>;

    return (
      <div>
        <div>
          {articleData}
        </div>
      </div>
    )
}