2015-07-04 16 views
8

解決,請參閱更新下面。您可以使用此代碼作爲參考來實現東西呈三角反應:等到所有的孩子都可用,然後調用函數


可以說我有一個父反應成分(ES6):

家長

import ChildDiv from './ChildDiv' 

export default React.createClass({ 
    displayName: 'ParentDiv', 

    getInitialState() { 
    nodesLoadedToCanvas: 0, 
    workedOnParentOnceAfterAllChildrenWereLoaded: false 
    }, 

    onChildNodeDidMount() { 
    let nodeCount = this.state.nodesLoadedToCanvas + 1 
    this.state.nodesLoadedToCanvas = nodeCount 
    console.log('Mount ' + this.state.nodesLoadedToCanvas + ' nodes so far') 
    }, 

    render() { 
    const {children} = this.props // 'children' is a model collection 

    return (
     <div id='ParentDiv'> 
     {children.map((childDiv) => 
     <ChildDiv data={childDiv} key={childDiv.id} onRender={this.onChildNodeDidMount}/> 
    )} 
     </div> 
    ) 
    }, 

    componentDidMount() { 
    console.log('Parent did mount') 
    }, 

    componentDidUpdate() { 
    let allNodesArePresent = (this.state.nodesLoadedToCanvas === this.props.children.length) 
    if (!this.state.workedOnParentOnceAfterAllChildrenWereLoaded) { 
     console.log('Do something') 
     this.state.workedOnParentOnceAfterAllChildrenWereLoaded= true 
    } 
    } 
}) 

和一個孩子組分像這

孩子

export default React.createClass({ 
    displayName: 'ParentDiv', 

    render() { 
    const {data} = this.props 

    return (
     <div id='ParentDiv'> 
     data.name 
     </div> 
    ) 
    }, 

    componentDidMount() { 
    console.log('ChildDiv did mount') 
    this.props.onRender() // tell parent that child did mount 
    }, 

    componentDidUpdate() { 
    } 
}) 

爲什麼我的控制檯說

Parent did Mount 
ChildDiv did Mount 
ChildDiv did Mount 
ChildDiv did Mount 

而且不

ChildDiv did Mount 
ChildDiv did Mount 
ChildDiv did Mount 
Parent did Mount 

如何在完整的父級(及其所有孩子)呈現後作出反應調用函數?

UPDATE

我加入了onRender={this.onChildNodeDidMount}參數來我的標籤(見上文),請致電ChildDiv的功能componentDidMount(),現在可以決定是否所有的節點都在裝有@nash_ag的輸入解決了這個我的父母componentDidUpdate()方法。我上面更新了我的代碼。

+0

你能詳細說一下你想做什麼嗎?日誌的順序是有意義的,因爲孩子不能在其父母之前在文檔中。但是,當調用componentDidMount時,所有組件都已經被渲染。 –

+0

我想用JSPlumb連接來連接孩子。爲此,他們必須出現在DOM上。如果我將connect-Operation放在'componentDidUpdate()'中,我的Connections將會被繪製(在一些失敗的嘗試之後),但是每次組件更新時都會重繪。這殺死了我的表現,並不好... – Benvorth

+0

它應該在componentDidMount –

回答

6

您可能可以使用componentDidUpdate()來檢查是否所有的孩子都已完成,因爲每次渲染動態孩子時都會調用它。

一旦收到最後一個(比較道具),你可以繼續進行進一步的處理。

+0

感謝您的輸入。你有關於如何最好地確定所有孩子是否都呈現的想法嗎? – Benvorth

+0

'React.Children'是可以幫助你的。檢查: https://facebook.github.io/react/docs/top-level-api.html#react.children –

+0

這對我來說非常合適,因爲我需要知道何時更新兒童道具的方法。謝謝! –

相關問題