[英]How to fetch Data before Render ReactJS
so I have this custom hook which returns an array of Objects from database, before it gets data, the value of returned value is undefined.所以我有这个自定义钩子,它从数据库返回一个对象数组,在它获取数据之前,返回值的值是未定义的。
getDataByID(100).doc?.items
- This returns the items from database as an array. getDataByID(100).doc?.items
- 这将作为数组从数据库返回项目。 How can I make sure that the returned Value is not undefined and then mount the component in functional components?如何确保返回的值不是未定义的,然后将组件安装在功能组件中?
Try to fetch this data in parent component, and when you received the data then only mount required component as child component and pass those data as props.尝试在父组件中获取此数据,当您收到数据时,仅将所需组件挂载为子组件并将这些数据作为道具传递。
{
(dataFromAPI !== undefined) ? <ChildComponent data={dataFromAPI} /> : undefined
}
In this way when you have dataFromAPI
then only your child component will be mounted.这样,当您拥有
dataFromAPI
只会安装您的子组件。
Mujibur Rehman Ansari 的回答可以进一步修改为
{ dataFromAPI && <ChildComponent data={dataFromAPI} /> }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.