[英]Use Async/Await with Axios in React.js
下列的
我正在嘗試在 React.js 應用程序中使用 Async/Await 向我的服務器發出一個簡單的獲取請求。 服務器在/data
加載一個簡單的 JSON,如下所示
JSON
{
id: 1,
name: "Aditya"
}
我可以使用簡單的 jquery ajax get 方法將數據獲取到我的 React 應用程序。 但是,我想利用 axios 庫和 Async/Await 來遵循 ES7 標准。 我當前的代碼如下所示:
class App extends React.Component{
async getData(){
const res = await axios('/data');
console.log(res.json());
}
render(){
return(
<div>
{this.getData()}
</div>
);
}
}
使用這種方法,我得到以下錯誤:
對象作為 React 子級無效(找到:[object Promise])。 如果您打算渲染一組子項,請改用數組。
我沒有正確實施它嗎?
兩個問題跳出來:
你的getData
永遠不會返回任何東西,所以它的承諾( async
函數總是返回一個承諾)如果它不拒絕,將用undefined
實現
錯誤消息清楚地表明您正在嘗試直接呈現承諾getData
返回,而不是等待它解決然后呈現履行值
解決 #1: getData
應該返回調用json
的結果:
async getData(){
const res = await axios('/data');
return await res.json();
}
地址 #2:我們必須查看更多您的代碼,但從根本上說,您不能這樣做
<SomeElement>{getData()}</SomeElement>
...因為那不會等待決議。 您需要使用getData
來設置狀態:
this.getData().then(data => this.setState({data}))
.catch(err => { /*...handle the error...*/});
...並在渲染時使用該狀態:
<SomeElement>{this.state.data}</SomeElement>
更新:現在你已經告訴我們你的代碼,你需要做這樣的事情:
class App extends React.Component{
async getData() {
const res = await axios('/data');
return await res.json(); // (Or whatever)
}
constructor(...args) {
super(...args);
this.state = {data: null};
}
componentDidMount() {
if (!this.state.data) {
this.getData().then(data => this.setState({data}))
.catch(err => { /*...handle the error...*/});
}
}
render() {
return (
<div>
{this.state.data ? <em>Loading...</em> : this.state.data}
</div>
);
}
}
進一步更新:您已經表示偏好在componentDidMount
使用await
而不是then
和catch
。 您可以通過在其中嵌套async
IIFE 函數並確保該函數不會拋出來做到這一點。 ( componentDidMount
本身不能是async
,沒有任何東西會消耗那個承諾。)例如:
class App extends React.Component{
async getData() {
const res = await axios('/data');
return await res.json(); // (Or whatever)
}
constructor(...args) {
super(...args);
this.state = {data: null};
}
componentDidMount() {
if (!this.state.data) {
(async () => {
try {
this.setState({data: await this.getData()});
} catch (e) {
//...handle the error...
}
})();
}
}
render() {
return (
<div>
{this.state.data ? <em>Loading...</em> : this.state.data}
</div>
);
}
}
根據過去幾個月的經驗,我意識到實現這一目標的最佳方法是:
class App extends React.Component{
constructor(){
super();
this.state = {
serverResponse: ''
}
}
componentDidMount(){
this.getData();
}
async getData(){
const res = await axios.get('url-to-get-the-data');
const { data } = await res;
this.setState({serverResponse: data})
}
render(){
return(
<div>
{this.state.serverResponse}
</div>
);
}
}
如果您嘗試對諸如單擊之類的事件發出發布請求,則在該事件上調用getData()
函數並像這樣替換它的內容:
async getData(username, password){
const res = await axios.post('url-to-post-the-data', {
username,
password
});
...
}
此外,如果您在組件即將加載時發出任何請求,那么只需將async getData()
替換為async componentDidMount()
並像這樣更改渲染函數:
render(){
return (
<div>{this.state.serverResponse}</div>
)
}
Async/Await with axios
useEffect(() => {
const getData = async () => {
await axios.get('your_url')
.then(res => {
console.log(res)
})
.catch(err => {
console.log(err)
});
}
getData()
}, [])
const axios = require('axios').default;
const sendGetRequest = async () => {
try {
const resp = await axios.get('https://jsonplaceholder.typicode.com/posts', {
headers: {
'authorization': 'Bearer YOUR_JWT_TOKEN_HERE'
}
});
console.log(resp.data);
} catch (err) {
// Handle Error Here
console.error(err);
}
};
sendGetRequest();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.