【问题标题】:How to get API call from wordpress with react js and axios?如何使用 react js 和 axios 从 wordpress 获取 API 调用?
【发布时间】:2017-07-18 03:57:09
【问题描述】:

我有一个问题,我无法使用 axios react js 从 wp API 获取数据 我的代码:

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

【问题讨论】:

标签: api reactjs call axios


【解决方案1】:

好的,找到了。

你根本不需要map这一步,数组已经在res中返回了。

替换:

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

与:

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

【讨论】:

  • 但是我在这个错误中遇到了问题 {this.state.posts.map(posts =>
  • {post.title}
  • )}但我 console.log(this.state.posts.map(posts => posts.id));就像那个输出是 id posts
  • 感谢这是工作{this.state.posts.map(data =>
  • {data.title.rendered}
  • )} 感谢您的帮助我,我很抱歉很麻烦你谢谢你的帮助谢谢你的帮助,因为我刚学了一周的react js
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签