javascript - 在后台渲染繁重的 React 组件
问题描述
我有一个递归组件,由于它的复杂性,它需要几秒钟来渲染。我检查了 DOM,结果发现包含该重组件的组件直到完全加载后才被插入。在此之前,页面只是空白。
const SomeElement = (props) => {
// ...
return (
<div> // not inserted into DOM until HeavyComponent fully loads
// expected behavior: First the Loading... label is displayed, then the contents of the HeavyComponent
// actual behavior: not rendered until HeavyComponent renders, thus Loading... label and the component shows up at the same time
<div>Loading...</div>
<HeavyComponent />
</div>
);
};
我想Loading...
在后台加载其他组件时显示消息,例如:
const [ heavyComponent, setHeavyComponent ] = useState(null);
React.asyncCreateElement(HeavyComponent, props)
.then((loadedComponent) => {
setHeavyComponent(loadedComponent)
})
if (!heavyComponent) {
return <div>Loading...</div>
}
return <div> { heavyComponent } </div>;
我能找到的最接近的是React.lazy
and Suspense
,但它并不真正符合我的用例 - 我希望它HeavyComponent
始终可见。使用代码拆分并没有改变行为。
所以重申一下:有没有办法在后台(比如在服务工作者中)呈现一个沉重的(不是因为异步,而是因为它的复杂性)组件?
解决方案
你能不能不做
const SomeElement = (props) => {
const [firstRender, setFirstRender] = useState(true);
useEffect(() => {
setFirstRender(false);
}, []);
return (
<div>
{ firstRender && <div>Loading...</div> }
{ !firstRender && <HeavyComponent /> }
</div>
);
};
这样你就得到了你想要的渲染,然后一旦它完成生成重组件将替换它?
推荐阅读
- c - 如何以随机方式在两个值之间进行选择?
- ios - ArKit3 的算法,BodyTracking
- tensorflow - 试图理解 tensorflow 数据集中小批量中的随机播放
- java - 如何使用 JOptionPane 删除 ArrayList 中的元素?
- javascript - 我可以在 React 中使用 switch 语句来管理我的表单吗?
- python - 删除边界线上方的图像顶部以检测文本文档
- javascript - 从单独的链接更改部分 href 不适用于从选择下拉列表中进行的更改
- javascript - react-native-video:无法读取 null 的属性“常量”
- java - 为什么我的底部导航栏不能显示?
- javascript - 将空数组作为第二个参数传递时,React Hook useEffect 缺少依赖项