React Axios更好的方法从WordPress REST获取单篇文章

时间:2018-08-02 10:57:13

标签: wordpress reactjs axios wordpress-rest-api

我正在使用以下内容从WordPress REST API获取单个帖子。

import React, { Component } from 'react';
import axios from 'axios';

class Post extends Component {

    constructor() {
    super();
    this.state = {
      post: [],
    };
  }

  componentDidMount() { 
    axios.get('http://example.com/wp-json/wp/v2/posts?slug=some-post')
    .then(response => {
      this.setState({ post: response.data });
    })
    .catch(error => {
        console.log(error);
    });
    }

  render() {
    return (

      <div>
        {this.state.post.map(single => {
            return(
            <div>
              <h1>{single.title.rendered}</h1>
              <p>{single.content.rendered}</p>
            </div>                                        
            );
        })}
      </div>
    );
  }
}

export default Post;

是否存在一种更好/更直接的方式来呈现帖子而不映射数组?

1 个答案:

答案 0 :(得分:1)

如果api返回数组,那么您只能使用第一个元素,例如:

this.setState({ post: response.data[0] });

当然,您应该使用一些条件渲染(地图适用于空数组):

if(!this.state.post) return <Loading />