无法在React.js中进行提取

时间:2018-07-01 05:37:08

标签: reactjs

我正在尝试获取以下端点输出的消息:

http://helloworld-env-2.5fwknpgms8.us-east-2.elasticbeanstalk.com/

我只是运行了一个create-react-app来创建我的应用程序,并更改了App.js文件中的代码

新代码:

import React, { Component } from 'react';
import './App.css';

class App extends React.Component {
  constructor(props){
    super(props);
    this.state = {
       error: null,
       isLoaded: false,
       items: ""
    };
  }

  componentDidMount(){
    console.log("mounting component");
    fetch("http://helloworld-env-2.5fwknpgms8.us-east-2.elasticbeanstalk.com/")
    .then((result) => {
      this.setState({
        isLoaded: true,
        items: result
      });
    });
  }

  render() {
    console.log("rendering");
    const isLoaded = this.state.isLoaded;
    if(isLoaded){
      return (<div> {this.state.items} </div>);
    }
    else{
    return (
      <div>loading</div>
    );
    }
  }
}

export default App;

我一直收到加载消息。

1 个答案:

答案 0 :(得分:2)

您需要解析提取的响应:

  componentDidMount(){
    fetch("http://helloworld-env-2.5fwknpgms8.us-east-2.elasticbeanstalk.com/")
    .then((result) => result.json()) // here
    .then((result) => {
      const { a } = result; // access 'a' key from response
      this.setState({
        isLoaded: true,
        items: a
      });
    });
  }

这里是docs