首页 > 解决方案 > 遍历 Wordpress 对象 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/BlogBu​​ilder/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;

标签: reactjs

解决方案


你不能map越过一个对象。它必须是一个数组。如果需要,可以使用以下方法将其转换为数组Object.values(post.categories)

<ul>
  {Object.values(post.categories).map((category) => {
    return(
      <li>{category.name}</li>
    );
  })};
</ul>

推荐阅读