使用 React、博客文章和 Wordpress API 进行动态路由 [英] Dynamic routing with React, Blog Posts and Wordpress API

查看:62
本文介绍了使用 React、博客文章和 Wordpress API 进行动态路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试按照本教程来感受一下动态路由如何工作.现在,我不想使用静态数据,而是想使用 WordPress 的 API 来提取博客文章,为每篇文章生成唯一的链接.我能够生成链接,但在新页面上没有生成任何数据.我在这里做错了什么?

Articles.js(用作抓取所有博客文章的预览页面,按预期工作)

import React, { Component } from 'react';从'react-router-dom'导入{链接,路由};从'./Article'导入文章;const newsURL = "http://myprivateblogapi.com/wp-json/wp/v2/posts?_embed";导出默认类文章扩展组件{构造函数(道具){超级(道具);this.state = {新闻数据:[],请求失败:假} }componentDidMount() {获取(新闻网址).then(响应 => {如果(!响应.确定){throw Error("网络请求失败.");}返回响应}).then(d => d.json()).then(d => {this.setState({新闻数据:d})}, () =>{this.setState({请求失败:true})}) }使成为() {让文章 = this.state.newsData.map((article, index) => {if(this.state.requestFailed) 返回 <p>Failed!</p>if(!this.state.newsData) 返回<p>加载中...</p>返回(<div key={index} className="article-container"><div className="文章预览"><span className="article-date">{article.date}</span><h5>{article.title.rendered}</h5><div risklySetInnerHTML={{ __html: article.excerpt.rendered }}/><Link to={`/news/${article.slug}`}>阅读更多...</Link>

<路由路径={`/news/:articleSlug`}渲染={(道具)=><文章数据={文章} {...道具}/>}/>

)});返回 (<div><h3>来自博客的所有文章</h3>{文章}

) } }

Article.js(渲染每篇文章)

从'react'导入React;const 文章 = ({match, data}) =>{让文章 = data.find(a => a.slug == match.params.articleSlug);让文章数据;如果(文章)文章数据 = 

<h3>{article.title.rendered}{ console.log(`${article.title.rendered}`) }<p>{article.content.rendered}</p>{ console.log(`${article.content.rendered}`) }<小时/>

别的文章数据 = <h2>对不起.那篇文章不存在.;返回 (<div><div>{文章数据}

)}导出默认文章;

解决方案

我认为问题出在这里:

render={ (props) =><文章数据={文章} {...道具}/>}/>

在文章中,您存储的是地图的结果,因此它不会包含您期望的数据:

让文章 = this.state.newsData.map(....)

解决方案:

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

render={ props =><文章数据={this.state.newsData} {...props}/>}/>

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

render={ props =><文章数据={文章} {...道具}/>}/>

文章组件:

const 文章 = ({match, data}) =>{让文章数据;如果(数据)文章数据 = 

<h3>{article.title.rendered}<p>{article.content.rendered}</p><小时/>

别的文章数据 = <h2>对不起.那篇文章不存在.;返回 (<div><div>{文章数据}

)}

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;

解决方案

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

这篇关于使用 React、博客文章和 Wordpress API 进行动态路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆