问题描述
我有一个 React 应用程序,它在不同组件中使用多个 fetch 调用.在主页组件中,我导入了较小的组件,它们都有自己的 fetch 调用.
I have a React app that uses multiple fetch calls throughout different components. In Home page component, I have imported smaller components, all of whom have it's own fetch call.
render() {
return (
<React.Fragment>
<Banner/>
<Services />
<About />
</React.Fragment>
)
}
Banner、Services 和 About 对不同的端点都有自己的 fetch 调用,现在我的问题是因为响应有点慢,如何等待所有子组件获取数据,然后渲染主页零件.我曾尝试将 isLoading 的状态放入并添加一个加载器以等待组件获取,但我不知道要等待什么才能将 isLoading 设置为 false.
Banner, Services and About have their own fetch calls to different endpoints, now my question is because the response is a little bit on the slower side, how to wait for all of the child components to fetch data, then render the Homepage component. I have tried to put the state of isLoading and add a loader to wait for components to fetch, but I don't know what to wait for to set isLoading to false.
推荐答案
你没有.相反,您将 fetches 移动到 Homepage 组件的父级,然后让该父级仅在 Homepage 组件拥有所有必要信息时才呈现该组件.用 React 的说法,这是提升状态"(例如,向上到父级).
You don't. Instead, you move the fetches to the Homepage component's parent, and then have that parent only render the Homepage component when it has all of the necessary information to do so. In React parlance, this is "lifting state up" (e.g., up the hierarchy to the parent).
虽然您可以以正在加载"的形式呈现主页,并让它以正在加载"的形式呈现其子组件,并让子组件回调到主页说他们现在有了自己的信息,这比简单地将状态提升到实际需要它的最高组件更复杂(因此它知道它可以呈现主页).
While you could render the Homepage in a "loading" form, and have it render its child components in a "loading" form, and have the child components call back to the Home page to say they have their information now, that's more complicated than simply lifting the state up to the highest component that actually needs it (so it knows it can render the Homepage).
这篇关于等待子组件获取数据,然后渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!