简体   繁体   中英

Can't display result of API request with React

I just started using React and I'm astounded at how incredibly difficult it is to do literally the most basic thing possible. All I want to do is make a request and display the response. Here's my code:

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>
        );
  }
}

I can't use await in render() without making it async, but I can't make it aysnc because then it will return a Promise. I can't use then() in render() because it will also return a Promise. I can't store the result of the call in state because it won't be there by the time render() is called. So what do I do??

Why is this so hard? Any decent language would allow be to just block on the API call.

await the response.json() and then return the data:

// 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;
}

and for your code:

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>
    );

} }

You might want to read up the React docs that talks about life cycle, props & states to implement what you want in the React way.

Typically, this kind of network requests are fired from componentDidMount , followed by a state change on the component when the network request completes.

https://facebook.github.io/react/docs/react-component.html#componentdidmount

And changes to states/props will automatically re-render the component.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM