我刚开始使用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调用。
等待,“任何体面的语言”会在网络通话期间冻结用户界面? – Bergi