解決,請參閱更新下面。您可以使用此代碼作爲參考來實現東西呈三角反應:等到所有的孩子都可用,然後調用函數
可以說我有一個父反應成分(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()
方法。我上面更新了我的代碼。
你能詳細說一下你想做什麼嗎?日誌的順序是有意義的,因爲孩子不能在其父母之前在文檔中。但是,當調用componentDidMount時,所有組件都已經被渲染。 –
我想用JSPlumb連接來連接孩子。爲此,他們必須出現在DOM上。如果我將connect-Operation放在'componentDidUpdate()'中,我的Connections將會被繪製(在一些失敗的嘗試之後),但是每次組件更新時都會重繪。這殺死了我的表現,並不好... – Benvorth
它應該在componentDidMount –