如何从wordpress获取API调用反应js和axios?

时间:2017-02-27 13:49:03

标签: api reactjs call axios

我遇到问题,我无法通过axios从js API获取数据反应js 我的代码:

var React = require('react');
var ReactDOM = require('react-dom');
var axios = require('axios');

var Wordpress = React.createClass({
    getInitialState: function() {
        return {posts: []};
    },
    componentDidMount() {
        axios.get(`http://localhost/scareid/wp-json/wp/v2/posts`).then(res => {
            const posts = res.data.map(obj => obj.data);
            this.setState({posts});
        });
    },
    render() {
        return (
            <div>

                <h1>{`/r/${this.props.title}`}</h1>
                <ul>

                    {this.state.posts.map(post => <li key={post.id}>{post.title}</li>)}
                </ul>
            </div>
        );
    }
})

module.exports = Wordpress;

我的api

http://pastebin.com/9x4rgJmE

控制台日志数据: enter image description here

1 个答案:

答案 0 :(得分:0)

好的发现了。

您根本不需要地图步骤,数组已在res中返回。

替换:

const posts = res.data.map(obj => obj.data);
            this.setState({posts});

使用:

if (res && res.data) {
 this.setState({
  posts: res.data 
 });
}