Dynamic routing with React, Blog Posts and Wordpress API

梦想与她 提交于 2019-12-11 00:12:44

问题


I tried following this tutorial to get a feel of how dynamic routing would work. Now instead of using static data, I want to pull in blog posts using WordPress' API to generate unique links for each post. I'm able to generate the link, but none of the data is generating on the new page. What am I doing wrong here?

Articles.js (serves as the preview page to grab all the blog posts, works as expected)

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>
    )   } }

Article.js (to render up each individual article)

import React from 'react';

const Article = ({match, data}) => {
  let article = data.find(a => a.slug == match.params.articleSlug);
  let articleData;

  if(article)
    articleData = <div>
      <h3> {article.title.rendered}</h3>
      { console.log(`${article.title.rendered}`) }
      <p>{article.content.rendered}</p>
      { console.log(`${article.content.rendered}`) }
      <hr />
    </div>
  else 
    articleData = <h2> Sorry. That article doesn't exist. </h2>;

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

export default Article;

回答1:


I think issue is here:

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

And in articles you are storing the result of map, so it will not have the data that you are expecting:

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

Solution:

1- If you want to pass the full array then write it like this (not a good idea):

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

2- Pass the single object and looping will be not required inside Article component:

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

And Article component:

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>
    )
}


来源:https://stackoverflow.com/questions/48459816/dynamic-routing-with-react-blog-posts-and-wordpress-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!