简体   繁体   English

如何在渲染 ReactJS 之前获取数据

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

相关问题 如何在reactjs中重复获取并呈现更新的api数据? - How to fetch repeatedly and render updated api data in reactjs? 如何根据ReactJS中的响应获取json数据并渲染组件(List) - how to fetch json data and render component (List) according to the response in ReactJS React.js:在组件安装之前如何获取要加载的数据? - Reactjs: How to fetch data to loaded before the component is mounted? ReactJS。 如何在Fetch API在componentWillReceiveProps中工作之前防止调用render() - ReactJS. How to prevent calling render() before Fetch API working in componentWillReceiveProps 如何在首次渲染之前在Redux中获取数据并将其设置为默认状态 - How to fetch data in redux before first render and set it to default state 如何在 React js 中渲染功能组件之前获取数据 - How to fetch data before render functionnal component in react js 在表格渲染 ReactJS 之前加载 API 数据 - Loading API data before Table render ReactJS ReactJS 在接收到要渲染的数据之前调用渲染方法 - ReactJS is calling the render method before it receives the data to render 如何在使用ReactJS过滤元素之前呈现元素? - How to render the elements before to filter elements with ReactJS? 使用 Reactjs 获取 GET 请求 - 如何在我的请求中实现可重用组件来呈现我的数据? - Fetch GET request with Reactjs - how do i implement a reusable component within my request to render my data?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM