reactjs - 遍历 Wordpress 对象 REACT js
问题描述
我是 REACT.js 的新手,非常感谢您的建议
- 我有一个类别列表,我在下面发布了一个帖子
- 我如何在 react js 中显示这些类别列表?
我尝试了以下方法:
<ul>
{post.categories.map((category) => {
return(
<li>{category.name}</li>
);
})};
</ul>
但我收到错误:TypeError:post.categories.map 不是函数
以下是我的文件
应用程序/scr/components/博客/Index.js
import React, { Component } from 'react';
import Layout from '../../components/Layout/Layout';
import { Link } from 'react-router-dom';
class Index extends Component {
render() {
return(
<Layout>
<ul>
{this.props.posts.map((post) => {
if (post) {
return(
<li key={post.ID} className="card">
<div>{post.title}</div>
<div>{post.date}</div>
<ul>
{post.categories.map((category) => {
return(
<li>{category.name}</li>
);
})};
</ul>
</li>
);
} else {
return null;
}
})}
</ul>
</Layout>
);
}
}
export default Index;
应用程序/scr/containers/BlogBuilder/BlogIndexBuilder.js
import React, { Component } from 'react';
import BlogIndex from '../../components/Blog/Index';
import axios from 'axios';
class BlogIndexBuilder extends Component {
state = {
posts: []
};
componentDidMount() {
axios
.get(
"http://public-api.wordpress.com/rest/v1/sites/emma.wordpress.com/posts"
)
.then(res => {
this.setState({ posts: res.data.posts });
console.log(this.state.posts);
})
.catch(error => console.log(error));
}
parseOutScripts(content) {}
render() {
return (
<div>
<BlogIndex
posts={this.state.posts}
/>
</div>
);
}
}
export default BlogIndexBuilder;
应用程序/scr/components/Layout/Layout.js
import React from 'react';
import Aux from '../../hoc/Aux';
const layout = (props) => {
return(
<Aux>
<main>{props.children}</main>
</Aux>
)
};
export default layout;
解决方案
你不能map
越过一个对象。它必须是一个数组。如果需要,可以使用以下方法将其转换为数组Object.values(post.categories)
:
<ul>
{Object.values(post.categories).map((category) => {
return(
<li>{category.name}</li>
);
})};
</ul>
推荐阅读
- android - 如何创建具有活动和其他第三方依赖项的 android 库
- scala - Scala - 高阶函数中的完美数字使用 - 有什么问题吗?
- python - 将数据从数据框附加到 JSON
- asynchronous - 使用c ++的Grpc异步双向客户端
- asp.net - 如何在 Asp.net 中隐藏错误请求 400 的响应标头
- python-3.x - 格式化电脑后出现编译问题
- php - 如何在 CodeIgniter 中使用 JWPlayer?
- docusaurus - 使侧边栏不可折叠并始终在 docusaurus V2 经典预设中展开
- python - Visual Studio Code:在没有相应 .py 文件的情况下使用 .pyd 文件时可以使用 Intellisense /“转到定义”吗?(pywin32)
- c# - 如何在 Polly 中创建策略以支持 http 响应 retry-after 标头