首页 > 解决方案 > 在后台渲染繁重的 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.lazyand Suspense,但它并不真正符合我的用例 - 我希望它HeavyComponent始终可见。使用代码拆分并没有改变行为。

所以重申一下:有没有办法在后台(比如在服务工作者中)呈现一个沉重的(不是因为异步,而是因为它的复杂性)组件?

标签: javascriptreactjs

解决方案


你能不能不做

const SomeElement = (props) => {
  const [firstRender, setFirstRender] = useState(true);
  useEffect(() => {
      setFirstRender(false);
  }, []);
  return (
    <div>
      { firstRender && <div>Loading...</div> }
      { !firstRender && <HeavyComponent /> }
    </div>
  );
};

这样你就得到了你想要的渲染,然后一旦它完成生成重组件将替换它?


推荐阅读