2017-09-27 24 views
3

我刚开始使用React时,我惊讶地发现,尽可能难以完成最基本的事情。我想要做的就是发出请求并显示响应。这里是我的代码:使用React无法显示API请求的结果

import React from 'react'; 
import 'whatwg-fetch'; 

export default class App extends React.Component { 
    async testBackend() { 
     let response = await fetch('http://localhost:8000/test', { credentials: 'include' }); 
     return response.json(); 
    } 

    render() { 
     let status = await this.testBackend(); 
     return (
      <div style={{ textAlign: 'center' }}> 
       <h1>Hello World</h1> 
       <p>{status}</p> 
      </div> 
     ); 
    } 
} 

我不能使用地等待着渲染()没有使它异步的,但我不能让它aysnc因为那会返回一个承诺。我不能在render()中使用then(),因为它也会返回一个Promise。我无法将调用的结果存储在状态中,因为调用render()的时候它不会存在。那么我该怎么做?

为什么这么难?任何体面的语言都可以阻止API调用。

+0

等待,“任何体面的语言”会在网络通话期间冻结用户界面? – Bergi

回答

0

等待response.json(),然后返回数据:

// async function 
async function fetchAsync() { 
    // await response of fetch call 
    let response = await fetch('https://api.github.com'); 
    // only proceed once promise is resolved 
    let data = await response.json(); 
    // only proceed once second promise is resolved 
    return data; 
} 

并为您的代码:

export default class App extends React.Component { 
    constructor(..args) { 
     super(..args); 
     this.state= { 
      status: '' 
     }; 
    } 
async testBackend() { 
    let response = await fetch('http://localhost:8000/test', { credentials: 'include' }); 
    let data = await response.text(); // for string 
    return data; 
} 

componentDidMount() { 
    this.testBackend().then((data) => { 
     this.setState({ 
      status: data 
     }) 
    } 
} 
render() { 

    return (
     <div style={{ textAlign: 'center' }}> 
      <h1>Hello World</h1> 
      <p>{this.state.status}</p> 
     </div> 
    ); 

}}