如何使用react js和axios从WordPress获取API调用?

ruoxqz4g  于 5个月前  发布在  iOS
关注(0)|答案(1)|浏览(45)

我有一个问题,我不能从WordPress的API与axios react 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
控制台日志数据:


的数据

2q5ifsrm

2q5ifsrm1#

好的找到了。
你根本不需要map这一步,数组已经在res中返回了。
替换:

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

字符串
使用:

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

相关问题