如何延迟渲染子组件的反应到父母组件完成获取?

发布于 2025-02-02 11:16:57 字数 1450 浏览 5 评论 0原文

我有一个从WebAPI获取的父组件,并将返回一系列人。 我还有一个孩子组件,该组件想从父母那里接收道具,其中从

我遇到的问题中获得道具,这似乎是在提取完成之前呈现儿童组件。 这是我的代码:

import React from "react";
import { Person} from "./Components";

export function Body({departmentId}){

const [peopleArray,setPeopleArray] = React.useState([]);

    React.useEffect(
        () => {
          const getPeopleArr = async () => {
          
            const response = await
             fetch(`https://xxxx`);           
             const data = await response.json();  
             setPeopleArray(data);       
              
          };
          getPeopleArr();
        }, []);

    return(
        <div>
            <Person name={peopleArray[0].personalDetails.name} position={peopleArray[0].department.name}/>      
        </div>
    );
}

正如您可以从上面看到的那样,最初,Peoperlearray是一个空数组。 React会给我带来错误“ Unturect typeError:无法读取未定义的属性(阅读'hersosyDetails')” 如果我删除代码&lt; person name = {peoperlearray [0] .personaldetails.name} position = {peoperlearray [0] .department.name}/&gt; 等一下,直到获取,然后快速粘贴代码,它成功地显示了人组成部分。

我试图在儿童组件中添加Settimeout,并尝试通过这样做几秒钟延迟它:

setTimeout(() => {
}, "2000")

但这似乎对问题没有帮助。

您能否建议SMTHG我可以在提取之前延迟渲染的孩子组成部分? 谢谢

编辑: 传递给孩子的每个道具创建多个用途(s

const [name,SetName] = data[0].personalDetails.name;
...

<Person name = {name}>

我能想到的一件事是为我想 ?作品...谢谢大家:D

I have a parent component that fetch from webAPI and will return an array of people.
I also have a child component that suppose to receive props from parent, in which props is obtained from the fetch

The problem I am having is it seems react renders the child component before the fetch is completed.
Here is my code:

import React from "react";
import { Person} from "./Components";

export function Body({departmentId}){

const [peopleArray,setPeopleArray] = React.useState([]);

    React.useEffect(
        () => {
          const getPeopleArr = async () => {
          
            const response = await
             fetch(`https://xxxx`);           
             const data = await response.json();  
             setPeopleArray(data);       
              
          };
          getPeopleArr();
        }, []);

    return(
        <div>
            <Person name={peopleArray[0].personalDetails.name} position={peopleArray[0].department.name}/>      
        </div>
    );
}

as you can see from above, initially peopleArray is an empty array. and react will give me the error "Uncaught TypeError: Cannot read properties of undefined (reading 'personalDetails')"
if I remove the code<Person name={peopleArray[0].personalDetails.name} position={peopleArray[0].department.name}/>
wait a bit until it fetched, and then quickly paste the code, it displays the Person component successfully.

I attempted to add SetTimeOut in the child component and try to delay it for few seconds, by doing:

setTimeout(() => {
}, "2000")

but this doesn't seem to help the issue.

Could you please suggest smthg that I can do to delay the child component from rendering before the fetch completed?
Thank you

Edit:
one thing I can think of was to create multiple useState(s) for each props I want to pass to the child, for example

const [name,SetName] = data[0].personalDetails.name;
...

<Person name = {name}>

but then if I have 20 props to pass, then I have to create 20 useState(s)

EDIT: The ? works... thanks guys :D

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

久隐师 2025-02-09 11:16:57

有几种解决这个问题的方法。

最简单的是使用可选的链接。类似的事情:

<Person name={peopleArray[0]?.personalDetails?.name} position={peopleArray[0]?.department?.name}/>

如果peopelearray [0]是未定义的,那么它不会渲染

其他任何解决方案是使用长度:

peopleArray.length > 0 && <Person name={peopleArray[0].personalDetails.name} position={peopleArray[0].department.name}/>

第三个是引入加载状态,默认情况下可以是真实的,您可以在解决Fetch解决后果之后将其更改为false

There are several ways to solve this problem.

The simplest is to use optional chaining. Something like this:

<Person name={peopleArray[0]?.personalDetails?.name} position={peopleArray[0]?.department?.name}/>

If peopleArray[0] is undefined, it won't render anything

Another solution is to use the length:

peopleArray.length > 0 && <Person name={peopleArray[0].personalDetails.name} position={peopleArray[0].department.name}/>

The third one is to introduce a loading state, which can be true by default, and you can change it to false after the fetch promise has been resolved

£烟消云散 2025-02-09 11:16:57

您应该首先检查变量是否没有空:

{peopleArray.length && <Person name={peopleArray[0]?.personalDetails.name} position={peopleArray[0]?.department.name}/> }

you should check first if the variable is not empty:

{peopleArray.length && <Person name={peopleArray[0]?.personalDetails.name} position={peopleArray[0]?.department.name}/> }
故事与诗 2025-02-09 11:16:57

只需引入一个诸如“加载”之类的状态,然后将您的孩子组件呈现:

已加载&amp; amp; &lt; childComponent /&gt; < /code>

在您的情况下:

import React from "react";
import { Person} from "./Components";

export function Body({departmentId}){

const [peopleArray,setPeopleArray] = React.useState([]);
const [loaded, setLoaded] = React.useState(false);

    React.useEffect(
        () => {
          const getPeopleArr = async () => {
          
            const response = await
             fetch(`https://xxxx`);           
             const data = await response.json();  
             setPeopleArray(data);       
              
          };
          await getPeopleArr();
          setLoaded(true);
        }, []);

    return(
        <div>
            {loaded && <Person name={peopleArray[0].personalDetails.name} position={peopleArray[0].department.name}/>}  
        </div>
    );
}

just introduce a state like "loaded" and then render your child component conditionally:

loaded && <ChildComponent />

In your case:

import React from "react";
import { Person} from "./Components";

export function Body({departmentId}){

const [peopleArray,setPeopleArray] = React.useState([]);
const [loaded, setLoaded] = React.useState(false);

    React.useEffect(
        () => {
          const getPeopleArr = async () => {
          
            const response = await
             fetch(`https://xxxx`);           
             const data = await response.json();  
             setPeopleArray(data);       
              
          };
          await getPeopleArr();
          setLoaded(true);
        }, []);

    return(
        <div>
            {loaded && <Person name={peopleArray[0].personalDetails.name} position={peopleArray[0].department.name}/>}  
        </div>
    );
}
山田美奈子 2025-02-09 11:16:57

您可以添加“?” peoperlearray [0]避免错误:

<Person name={peopleArray[0]?.personalDetails.name} position={peopleArray[0]?.department.name}/>

或者您可以使用条件渲染:

<div>
 {peopleArray[0] ? <Person name={peopleArray[0].personalDetails.name} 
 position={peopleArray[0].department.name}/> : null }    
</div>
 

You can add "?" after peopleArray[0] to avoid error:

<Person name={peopleArray[0]?.personalDetails.name} position={peopleArray[0]?.department.name}/>

Or you can use conditional render:

<div>
 {peopleArray[0] ? <Person name={peopleArray[0].personalDetails.name} 
 position={peopleArray[0].department.name}/> : null }    
</div>
 
海的爱人是光 2025-02-09 11:16:57

快速修复,只是检查数组的长度:

return peopleArray.length ? <Person name={peopleArray[0].personalDetails.name} position={peopleArray[0].department.name}/> : <></>

尽管它不考虑获取结果为空数组时的情况

Quick fix, is just to check the array's length:

return peopleArray.length ? <Person name={peopleArray[0].personalDetails.name} position={peopleArray[0].department.name}/> : <></>

Though it doesn't consider the case when fetched result is empty array

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文