[英]Can't display result of API request with React
我剛剛開始使用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調用。
等待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>
);
}}
您可能想要閱讀React文檔,這些文檔討論生命周期,道具和狀態,以React方式實現您想要的內容。
通常,這種網絡請求是從componentDidMount
觸發的,然后在網絡請求完成時對組件進行狀態更改。
https://facebook.github.io/react/docs/react-component.html#componentdidmount
對states / props的更改將自動重新呈現組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.