我刚刚开始使用 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。我无法将调用的结果存储在状态中,因为调用 render() 时它不会存在。那我该怎么办??
为什么这么难?任何像样的语言都允许阻止 API 调用。
最佳答案
您可能想阅读有关生命周期、 Prop 和状态的 React 文档,以以 React 方式实现您想要的内容。
通常,这种网络请求是从 componentDidMount
触发的,然后在网络请求完成时组件的状态发生变化。
https://facebook.github.io/react/docs/react-component.html#componentdidmount
状态/属性的更改将自动重新渲染组件。
关于javascript - 无法使用React显示API请求的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46440791/