最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

plugin development - WordPress with React: Saving and Using Data Collected with fetch

programmeradmin1浏览0评论

I am trying to do a basic thing with react, which is access an endpoint created by my locally installed WordPress website so that I can use that data and render it in a way I like.

import React, { Component } from 'react';
import PropTypes from 'prop-types';

export default class Widget extends Component {
  constructor(props) {
    super(props);

    var data = fetch("http://localhost:8888/test-site/wp-json/wp/v2/posts")
      .then(data => data.json())
      .then(data => {
        console.log(data);


        // this.state = {
        //   value: 'foo2',
        //   posts: data.value,
        // };

      })


    this.state = {
      value: 'foo2',
      posts: data.value,
    };

  }


  render() {
    return (
      <div>
        <p>value: {this.state.posts}</p>
      </div>
    );
  }
}

Widget.propTypes = {
  wpObject: PropTypes.object
};

I am trying to set the state to the data but it is returned as a promise. Apparently I can console.log the data but I cannot use it in the render function. You can see that I try to set the state in the second .then() but when I uncomment that and delete the thing below it everything stops working. If I cannot set the state inside the .then() how do I use the returned data in the render() function?

发布评论

评论列表(0)

  1. 暂无评论