admin管理员组

文章数量:1420907

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?

本文标签: plugin developmentWordPress with React Saving and Using Data Collected with fetch