2016-06-28 73 views
2

docs說:爲什麼高級組件中的componentDidMount不止一次調用?

初步呈現發生後調用一次,只有客戶端(而不是服務器上),請立即 。

現在,當我嘗試創建一個高階組件:

import React from 'react'; 
import { connect } from 'react-redux'; 

function wrap(Wrapped) { 

    class Wrapper extends React.Component { 
    componentDidMount() { 
     // I will place some reusable functionality here which need to 
     // be called once on mounted. 
     console.log('wrapper component mounted'); 
    } 
    render() { 
     return <Wrapped {...this.props}/> 
    } 
    } 
    return Wrapper; 
} 

class Wrapped extends React.Component { 
    componentDidMount() { 
    console.log('wrapped component mounted'); 
    } 
    render() { 
    return <div></div>; 
    } 
} 

connect()(wrap(Wrapped)); 

現在,每次出現在道具的任何變化時,控制檯將打印:

'wrapped component mounted' 
'wrapper component mounted' 

如果我刪除Wrapper,它只會打印一次(當第一次安裝 時):

`wrapped component mounted` 

那麼,爲什麼componentDidMount在高階組件中多次調用?

+0

connect()(wrap(Wrapper)); < - 用包裹替換 –

+0

@ffxsam對不起如果我不正確地理解你的評論,我的英語不太好。但是,如果我沒有錯,那麼當這些組件('Wrapper'和'Wrapped')已經掛載時,只要未卸載componentDidMount,它將不會被再次調用。我的意思是這兩個'componentDidMount'總是被調用,只要道具改變了。 –

+0

哦,對不起!我錯過了關於導致'componentDidMount'再次觸發的道具變化的部分。很奇怪。 – ffxsam

回答

1

connect()(wrap(Wrapper)); < - 替換爲包裝

我已經測試過它。它的工作原理。

function wrap(Wrapped) { 
    class Wrapper extends React.Component { 
    componentDidMount() { 
     console.log('wrapper component mounted'); 
    } 
    render() { 
     return <Wrapped {...this.props}/> 
    } 
    componentDidUpdate(prevProps, prevState){ 
     console.log(this.props); 
    } 
    } 
    return Wrapper; 
} 
class Wrapped extends React.Component { 
    componentDidMount() { 
    console.log('wrapped component mounted'); 
    } 
    componentDidUpdate(prevProps, prevState){ 
     console.log(this.props); 
    } 
    render() { 
    return <div></div>; 
    } 
} 

connect(state=>({state}))(wrap(Wrapped)); 

包裝FUNC返回包裝,你無法通過包裝成包FUNC。它的循環

+0

對不起,我錯過了輸入問題時打字。我更新了問題 –

+0

,但它只調用一次componentDidMount –

+0

你確定嗎?你是如何測試的?它在我的情況下每次都被調用。 –

相關問題