【问题标题】:Can't display result of API request with React无法使用 React 显示 API 请求的结果
【发布时间】:2018-03-08 12:34:02
【问题描述】:

我刚开始使用 React,我惊讶地发现要真正做到最基本的事情是多么困难。我要做的就是提出请求并显示响应。这是我的代码:

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

我不能在 render() 中使用 await 而不让它异步,但我不能让它 aysnc 因为那样它会返回一个 Promise。我不能在 render() 中使用 then(),因为它也会返回一个 Promise。我无法将调用结果存储在 state 中,因为在调用 render() 时它不会存在。那我该怎么办??

为什么这么难?任何体面的语言都允许只是阻止 API 调用。

【问题讨论】:

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

标签: javascript reactjs async-await


【解决方案1】:

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

} }

【讨论】:

    【解决方案2】:

    您可能需要阅读有关生命周期、道具和状态的 React 文档,以便以 React 方式实现您想要的。

    通常,此类网络请求从componentDidMount 触发,然后在网络请求完成时更改组件的状态。

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

    并且更改状态/道具将自动重新渲染组件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-21
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多