[英]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. 我刚刚开始使用React,我很惊讶于从字面上做最基本的事情是多么困难。 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. 我不能在render()中使用await而不使它成为异步,但我无法使它成为aysnc,因为它会返回一个Promise。 I can't use then() in render() because it will also return a Promise. 我不能在render()中使用then(),因为它也会返回一个Promise。 I can't store the result of the call in state because it won't be there by the time render() is called. 我无法将调用的结果存储在状态中,因为在调用render()时它不会存在。 So what do I do?? 那我该怎么办?
Why is this so hard? 为什么这么难? Any decent language would allow be to just block on the API call. 任何体面的语言都可以阻止API调用。
await the response.json() and then return the data: 等待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;
}
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. 您可能想要阅读React文档,这些文档讨论生命周期,道具和状态,以React方式实现您想要的内容。
Typically, this kind of network requests are fired from componentDidMount
, followed by a state change on the component when the network request completes. 通常,这种网络请求是从componentDidMount
触发的,然后在网络请求完成时对组件进行状态更改。
https://facebook.github.io/react/docs/react-component.html#componentdidmount https://facebook.github.io/react/docs/react-component.html#componentdidmount
And changes to states/props will automatically re-render the component. 对states / props的更改将自动重新呈现组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.