[英]`object' is undefined due to async function that fetched data in useEffect hook in reactjs
I am fetching an object
from api
using axios.get("url")
.我正在使用
axios.get("url")
从api
获取object
。 The object fetched successfully (in Animal
state) but there is a component level state (imageState)
which requires updation using setState
with fetched data. object 已成功提取(处于
Animal
状态),但有一个组件级别state (imageState)
需要使用带有提取数据的setState
进行更新。
Code:代码:
Component:零件:
import React,{useEffect, useState} from 'react'
import axios from 'axios'
const AnimalDetail = ({match}) => {
const [Animal ,setAnimal ] = useState({})
const Id = parseInt(match.params.id)
const [imageState, setImageState] = useState ("");
useEffect(()=>{
const fetchAnimal = async () => {
const {data} = await axios.get(`/api/animals/${Id}`)
setAnimal(data)
}
fetchAnimal()
// setImageState(Animal.image[0]) // need to access first index of image object
},[])
useEffect(()=>{
setImageState(Object.values(Animal.image)[0]) // error cant convert undefined to object
}
return (
<>
<h2>imageState </h2> //undefined
<h2>{typeof(Animal.image)}</h2> //gives object
</>
)
}
export default AnimalDetail
Backend Api:后端 Api:
{"id":2,
"image":["/image.jpg","/image2.jpg"],
"price":60000,
"breed":"",
"isAvailable":true,
"weight":110,
}
How can i fetch the data and update the component level state periodically(after fetching)?我如何获取数据并定期更新组件级别 state(获取后)?
You can try following, maybe this can help you.您可以尝试关注,也许这可以帮助您。 Removed the second
useEffect
and updated the image state in the first useEffect
.删除了第二个
useEffect
并更新了第一个 useEffect 中的图像useEffect
。
And also I can see, you have declared const [imageState, setImageState] = useState ("");
而且我还可以看到,您已声明
const [imageState, setImageState] = useState ("");
twice.两次。 You can remove the second one.
您可以删除第二个。
Also, make sure you handle the API error in useEffect
otherwise this may break the application on API failure.另外,请确保您处理了 useEffect 中的
useEffect
错误,否则这可能会在 API 失败时中断应用程序。
import React, { useEffect, useState } from 'react';
import axios from 'axios';
const AnimalDetail = ({ match }) => {
const [Animal, setAnimal] = useState({});
const Id = parseInt(match.params.id);
const [imageState, setImageState] = useState('');
useEffect(() => {
const fetchAnimal = async () => {
const { data } = await axios.get(`/api/animals/${Id}`);
setAnimal(data);
setImageState(data.image[0]);
};
if (Id) {
fetchAnimal();
}
}, [Id]);
return (
<>
<h2>imageState </h2> //undefined
<h2>{typeof Animal.image}</h2> //gives object
</>
);
};
export default AnimalDetail;
your code has some error in the second useEffect.您的代码在第二个 useEffect 中有一些错误。 you can use this one:
你可以使用这个:
useEffect(() => {
if (Animal) setImageState(Object.values(Animal.image)[0]); // error cant convert undefined to object
}, [Animal]);
this is because the Animal should have value first.这是因为 Animal 应该首先具有价值。 and you are defining imageState two times in your code.
并且您在代码中定义了两次 imageState。 the first one is enough.
第一个就够了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.