gpt4 book ai didi

javascript - 使用 React、博客文章和 Wordpress API 进行动态路由

转载 作者:行者123 更新时间:2023-11-29 23:27:43 26 4
gpt4 key购买 nike

我尝试关注 this tutorial了解动态路由的工作原理。现在我不想使用静态数据,而是想使用 WordPress 的 API 提取博客文章,为每篇文章生成唯一的链接。我能够生成链接,但新页面上没有生成任何数据。我在这里做错了什么?

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

Article.js(呈现每篇文章)

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;

最佳答案

我认为问题出在这里:

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

并且在文章中你存储的是 map 的结果,所以它不会有你期望的数据:

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

解决方案:

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

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

2- 传递单个对象并且在 Article 组件内不需要循环:

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

文章组件:

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

关于javascript - 使用 React、博客文章和 Wordpress API 进行动态路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48459816/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com