反应:等到所有孩子都可以使用并在之后调用一次函数

Ben*_*rth 11 javascript ecmascript-6 reactjs

解决了,请参阅下面的更新.您可以使用此代码作为参考来实现simillar


假设我有一个父反应组件(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
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

还有像这样的儿童组件

儿童

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 () {
  }
})
Run Code Online (Sandbox Code Playgroud)

为什么我的控制台说

Parent did Mount
ChildDiv did Mount
ChildDiv did Mount
ChildDiv did Mount
Run Code Online (Sandbox Code Playgroud)

并不是

ChildDiv did Mount
ChildDiv did Mount
ChildDiv did Mount
Parent did Mount
Run Code Online (Sandbox Code Playgroud)

在呈现完整父级(及其所有子级)之后,如何使反应调用函数?

UPDATE

我通过输入@nash_ag解决了这个问题,方法是onRender={this.onChildNodeDidMount}在我的标签中添加一个参数(见上文),在ChildDiv中调用函数,componentDidMount()现在可以决定是否所有节点都加载在我的父componentDidUpdate()方法中.我更新了上面的代码.

nit*_*gar 6

您可以使用它componentDidUpdate()来检查是否所有子项都已完成,因为每次渲染动态子项时都会调用它.

收到最后一个(从道具比较)后,您可以继续进行进一步处理.