【问题标题】:React: Wait until all childs are avaiable and call a function once afterwards反应:等到所有孩子都可用,然后再调用一次函数
【发布时间】:2015-09-22 00:17:43
【问题描述】:

已解决,请参阅下面的更新。您可以使用此代码作为参考来实现类似的东西


假设我有一个父反应组件(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

?

如何在渲染完整的父级(及其所有子级)后让 react 调用一个函数?

更新

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

【问题讨论】:

  • 你能详细说明你想做什么吗?日志的顺序是有意义的,因为孩子不能在其父母之前出现在文档中。但是,当调用 componentDidMount 时,所有组件都已渲染。
  • 我想用 JSPlumb Connection 连接孩子们。为此,它们必须存在于 DOM 上。如果我将连接操作放在componentDidUpdate() 中,我的连接将被绘制(在一些失败的尝试之后),但每次组件更新时都会重新绘制。这会扼杀我的表现并且不好......
  • 它应该可以在 componentDidMount 中正常工作
  • 不。 JSPlumb 打印到我的控制台`无法建立连接 - 源不存在'
  • 嗯。我不再知道 jsPlumb 是如何工作的。你如何告诉 jsplumb 使用哪些元素?

标签: javascript reactjs ecmascript-6


【解决方案1】:

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

一旦收到最后一个(与道具比较),您就可以继续进行进一步处理。

【讨论】:

  • 感谢您的意见。您是否知道如何最好地确定是否所有孩子都进行了渲染?
  • React.Children 可能会有所帮助。检查:facebook.github.io/react/docs/top-level-api.html#react.children
  • 这对我来说非常有效,因为我需要一种方法来知道何时更新子道具。谢谢!
  • 仅供参考,请注意不要通过在 componentDidUpdate() 中设置状态而导致无限循环,而无需某种中断来阻止它每次设置状态。我知道,因为我自己做的。
猜你喜欢
  • 2014-05-06
  • 1970-01-01
  • 2018-08-03
  • 2021-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多