我正在使用以下内容从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 回答
如果api返回数组,那么你只能取第一个元素,f.e . :
当然你应该使用一些条件渲染(map使用空数组):