React:Http请求响应没有显示在render()中

时间:2017-08-11 05:22:12

标签: reactjs http httprequest

有人可以告诉我下面的代码有什么问题吗?我正在使用' superagent'向Darksky API发出HTTP请求。然后尝试在没有工作的h2中显示结果。我尝试将其记录到控制台并且它完美地工作但是如果我试图在页面上显示它它不起作用。有人可以帮我解决,我是新手做出反应,不知道出了什么问题。

import React, { Component } from "react";
import "./Body.css";
import Request from "superagent";

class Body extends Component {
  constructor() {
    super();
    this.getData = this.getData.bind(this);
  }

  getData() {
    var url = this.props.apiUrl;
    Request.get(url)
      .then(response => {
        return(JSON.stringify(response.currently.summary));
      })
      .catch(error => {});
    }

  render() {
    <div>
      <h2>
        {this.getData()}
      </h2>
    </div>
  }
}

export default Body;

这是我导入Body.js的另一个文件: -

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

class App extends Component {
  render() {
      return <Body
apiUrl="https://api.darksky.net/forecast/42a9693aecf45c358afbda0022c5cf65/28.5355,77.3910" />;
  }
}

export default App;

2 个答案:

答案 0 :(得分:2)

您需要在组件的状态下设置数据,它会触发新的渲染:

  constructor() {
    super();
    this.getData = this.getData.bind(this);
    this.state = {data: {}}
  }

  componentDidMount() {
    var url = this.props.apiUrl;
    Request.get(url)
      .then(response => this.setState({data: JSON.stringify(response.currently.summary)}))
      .catch(error => {});
    }
render(){
    console.log("your data", this.state.data);
    return <div>test</div>;
}

使用this.state.data处理此数据。 我建议您将getData()功能更改为componentDidMount mehtod。

答案 1 :(得分:2)

您应该使用life cycle method(componentDidMount)并使用state。建议在componentDidMount()方法中进行HTTP调用。

constructor() {
    super();
    this.state = {
                   result: ''
                  };
}

componentDidMount(){

    var url = this.props.apiUrl;
    Request.get(url)
      .then(response => {

             this.setState({
                 result: JSON.stringify(response.currently.summary)
             });
      })
      .catch(error => {});
}

render() {
    <div>
      <h2>
        {this.state.result}
      </h2>
    </div>
}