簡體   English   中英

componentDidMount 和 React.lazy

[英]componentDidMount and React.lazy

我正在更改我的 React 應用程序以使用 React.lazy 來延遲加載組件。 當前的代碼庫使用 componentDidMount 來執行許多涉及子組件的操作,一旦安裝了組件。 現在我正在延遲加載組件,在子組件完成加載之前調用 componentDidMount 生命周期方法,因此在執行 componentDidMount 期間組件不可用。 我的理解是有一個占位符元素呈現給 DOM,它在技術上是“掛載”的,這就是調用 componentDidMount 生命周期方法的原因。 但這會導致我目前在 componentDidMount 中的邏輯出現問題。 為了使這更具體,我的應用程序代碼如下所示:

const SomeOtherComponent = React.lazy(() => import("/path/to/SomeOtherComponent.js"));

class SomeComponent extends Component {
    componentDidMount() {
        // perform operations on components rendered during render()
    }

    render() {
        <Suspense fallback="<div>Loading...</div>">
            <SomeOtherComponent/>
        </Suspense>
    }
}

componentDidMount 方法會在 render() 之后立即調用,盡管 SomeComponent 尚未安裝。 在安裝所有呈現的組件之前,似乎不應調用 componentDidMount 。 我錯過了一些明顯的東西嗎? 我是否需要重寫大部分代碼才能使用 React.lazy?

首先,你的lazy聲明應該在渲染函數之外。

// move this line outside the render function
const SomeComponent = React.lazy(() => import("/path/to/SomeComponent.js"));

class SomeComponent extends Component {
...

其次, lazyasync ——當componentDidMount被調用時,有一個Suspense組件已經渲染並且沒有子組件(因為Suspense被拋出了一個承諾並且在承諾解決之前不會渲染它的孩子)。

    componentDidMount() {
       // when this method is called, `SomeComponent` 
       // doesn't exist because `Suspense` doesn't render it's children 
       // until they are ready
       // in short, componentDidMount is called synchronously 
       // (when the component renders, all components must render synchronously) 
       // but the tree generated by `SomeComponent` is async (because it's `lazy`) 
       // and is not available by the time this method is called.
    }

    render() {
        <Suspense fallback="<div>Loading...</div>">
            <SomeComponent/>
        </Suspense>
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM