reactjs - Axios get request returns undefined for the first time in React
问题描述
I am using DRF for creating the api.. I am able to fetch the data using axios, but it returns undefined the first time and hence, when I use useState
, it gets set as undefined..
ItemDetail.js:
import React, { useState, useEffect } from 'react'
import axios from 'axios'
const ItemDetail = () => {
const [detail, setDetail] = useState('')
const [id, setId] = useState('')
const RecipeDetail = async () => {
const res = await axios({
method: 'get',
url: `http://127.0.0.1:8000/api/recipe-detail/1`,
headers: {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
}
})
setDetail(res.data)
}
useEffect(() => {
RecipeDetail()
}, [id])
console.log(`Hi ${detail}`)
return (
<div>
Hi
</div>
)
}
export default ItemDetail
So why is the API returning undefined for the first time?
I read few answers regarding the use of async/await which I have.. Also, when I console.log(detail)
, it logs it multiple times.. Why is that so?
As u can see in the image, it logs multiple times..
解决方案
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const ItemDetail = () => {
const [detail, setDetail] = useState('');
const RecipeDetail = async () => {
const res = await axios({
method: 'get',
url: 'http://127.0.0.1:8000/api/recipe-detail/1',
headers: {
'Content-Type': 'application/json;charset=UTF-8',
'Access-Control-Allow-Origin': '*',
},
});
setDetail(res.data);
};
useEffect(() => {
RecipeDetail();
}, [detail]);
console.log(`Hi ${detail}`);
return (
<div>
{detail ? 'Hi' : 'Loading ... '}
</div>
);
};
export default ItemDetail;
推荐阅读
- java - 图片按钮下方需要文字
- python - 带有可选关键字参数的 scipy.sparse.linalg.LinearOperator
- flutter - 子容器的高度取决于父容器的 Widget
- php - SQLSTATE [HY093]:无效的参数号:参数未在发布请求中定义
- scala - 如何在运行时在scala中查找类参数数据类型
- navision - 如何使用 Import-NAVApplicationObject 命令使用导出的 *.fob 更新 NAV2018
- excel - 如何将两个表合并为一个完整的表并使用标准一起删除重复项
- c - 我试图将一个 txt 文件读入一个链表,其中包含一行中的整数和字符串,用逗号分隔
- python - Python tkinter 创建具有不同图层的图像?
- node.js - 服务器启动失败,出现“必须定义 apiKey 值!”