类似 componentDidUpdate 的事件,但只触发一次

Event like componentDidUpdate, but fired only once

我有一些组件应该在它们的数据到达并首次呈现后立即做一些工作,但不是为了将来的重新呈现。例如:加载和呈现评论,现在 1. 加载社交媒体库和 2. 加载一些 Google 分析。

现在我就是这样做的:

componentDidUpdate: function (prevProps, prevState) {
    if (this.hasAlreadyUpdatedOnce) {
        // ... do some stuff...
    } else {
        // ... do some stuff that should happen only once...
        // 1. load social media libraries
        // 2. load some Google Analytics
        this.hasAlreadyUpdatedOnce = true;
    }
}

但我在问自己是否有比这样设置 属性 更优雅的方法。

你想要componentDidMount()Details here.

您是否尝试过在 ajax 调用结束后更新状态? 或者你可以 return false for componentShouldUpdate 并且一旦 ajax 调用承诺已经解决调用 forceUpdate.

我不能给你一个明确的答案,因为我不知道你的 ajax 调用是在父组件还是子组件中,但无论哪种方式你都应该能够利用 shouldComponentUpdate() 来实现你的目标。如果你真的不想在 ajax 调用后更新你的组件,那么你可以这样做: 应该组件更新(){ return 错误; }

然后当您的 ajax 电话回来时 运行 this.forceUpdate()。 returning false 将使您的组件永远不会更新,除非您 运行 this.forceUpdate()。然而,这不是问题的最佳解决方案,如果没有更多信息,我无法给出更好的解决方案。

假设您正在响应状态更改,您应该将回调作为第二个参数传递给 setState。

componentDidMount: function(){
  ajaxyThing(function(data){
    this.setState({data: data}, function(){
      // this.state is updated, the component has rerendered 
      // and the dom is current
    });
  }.bind(this));
}

React docs have a good example on how to handle this using isMounted()

isMounted() returns true if the component is rendered into the DOM, false otherwise. You can use this method to guard asynchronous calls to setState() or forceUpdate().

例子

首先,在 `getInitialState()' 中初始化您的状态变量:

getInitialState: function() {
  return {
    username: '',
    lastGistUrl: ''
  }
}

componentDidMount() 中进行 ajax 调用(在本例中为 $.get)然后重新设置状态变量:

componentDidMount: function() {
  $.get(this.props.source, function(result) {
    var lastGist = result[0];
    if (this.isMounted()) {
      this.setState({
        username: lastGist.owner.login,
        lastGistUrl: lastGist.html_url
      });
    }
  }.bind(this));
}