简体   繁体   English

由于异步 function 在 reactjs 中的 useEffect 钩子中获取数据,因此未定义“对象”

[英]`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.

相关问题 在自定义挂钩中渲染使用 useEffect 获取的数据时出现问题 - Issues rendering data fetched with useEffect in a custom hook 在 useEffect 钩子的 if 条件内调用异步 function - Calling an async function inside the if condition of useEffect hook 异步 function 在 UseEffect Hook 中不工作 - Async function not working inside UseEffect Hook React - 无法在 useEffect 挂钩之外访问获取的数据 - React - Cannot access fetched data outside useEffect hook 将 useEffect 钩子与“异步”一起使用 - Using useEffect hook with "async" useEffect 挂钩中的异步/等待不会等待 function - Async/await in useEffect hook doesn't await a function React useEffect hook和Async / await自带的fetch数据函数? - React useEffect hook and Async/await own fetch data func? useEffect 中异步 function 的 React Hook 警告:useEffect function 必须返回清理 function 或什么都不返回 - React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing 如果我使用异步函数,reactJS 中的 useEffect 也不是立即的 - useEffect is not immediate in ReactJS also if I use an async function 使用 useEffect 挂钩获取的项目列表仅在使用 useEffect 过滤后才会呈现 - Item list fetched with useEffect hook renders only after it is filtered with useEffect
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM