在React中渲染组件

发布于 2025-01-24 06:41:05 字数 197 浏览 4 评论 0原文

我有两个组件。组件 a 和组件 b 。我想在组件 a 完全渲染后渲染组件 b 。我使用useeffectuselayouteffect挂钩,但是这些对我没有帮助。您的解决方案是什么?

I have two components. component A and component B. I want to render component B after component A is fully rendered. I used useEffect and uselayoutEffect hooks, but those didn't help me. What's your solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

溺孤伤于心 2025-01-31 06:41:05

渲染组件 a uselayouteffect 和组件 b

useEffect(() => {}, [])

i特别喜欢 反应lazy lazy loading 组件

Render component A with uselayoutEffect and component B with

useEffect(() => {}, [])

I specifically prefer React Lazy Loading components

半世蒼涼 2025-01-31 06:41:05

下面的示例是使用使用>使用进行工作。一旦呈现&lt; app /&gt; < /code>,这意味着&lt; componenta /&gt; < /code>是因为它是其子女之一,因此我们可以使用使用使用更新状态并渲染&lt; componentb/&gt;

const { useState, useEffect } = React

function ComponentA() {
  return <div>A</div>
}

function ComponentB() {
  return <div>B</div>
}

function App() {
  const [componentALoaded, setComponentALoaded] = useState(false)
  useEffect(() => {
    setCompALoaded(true)
  }, [])

  return (
    <div>
      <ComponentA />
      {componentALoaded && <ComponentB />}
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>

但是,如果您想使用很多组件进行此操作,这可能不是很有效。

The following example is working using useEffect. Once <App /> is rendered, that means <ComponentA /> is rendered because it is one of its children, so we can use useEffect to update the state and render <ComponentB />:

const { useState, useEffect } = React

function ComponentA() {
  return <div>A</div>
}

function ComponentB() {
  return <div>B</div>
}

function App() {
  const [componentALoaded, setComponentALoaded] = useState(false)
  useEffect(() => {
    setCompALoaded(true)
  }, [])

  return (
    <div>
      <ComponentA />
      {componentALoaded && <ComponentB />}
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById("root"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="root"></div>

However, it may not be very efficient if you want to do this with a lot of components.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文