Javascript 确保在componentDidUpdate()和componentDidMount()中只运行一次

Javascript 确保在componentDidUpdate()和componentDidMount()中只运行一次,javascript,jquery,meteor,reactjs,Javascript,Jquery,Meteor,Reactjs,如果我有一个初始化某个东西的方法(比如jQuery小部件),我如何确保只调用一次initialize,但是在刷新和在没有刷新的情况下导航到该页面时调用initialize呢。我目前的做法如下: // key used to make sure initialize() only runs in one of DidUpdate/DidMount let key = 0; Component = React.createClass({ mixins: [ReactMeteorData],

如果我有一个初始化某个东西的方法(比如jQuery小部件),我如何确保只调用一次initialize,但是在刷新和在没有刷新的情况下导航到该页面时调用initialize呢。我目前的做法如下:

//  key used to make sure initialize() only runs in one of DidUpdate/DidMount
let key = 0;

Component = React.createClass({
  mixins: [ReactMeteorData],
  hasKey() {
    return key;
  },
  getKey() {
    key = 1;
  },
  resetKey() {
    key = 0;
  },
  componentDidUpdate() {
    if (!(this.hasKey())) {
      initialize()();
      this.getKey();
    }
  },
  componentDidMount() {
    if (!(this.hasKey())) {
      initialize()();
      this.getKey();
    }
  },
  componentWillUnmount() {
    this.resetKey();
  }
}})

我认为您可以在构造函数中创建默认为false的属性,例如didMount、didUpdate。componentDidMount将只被调用一次,因此您可以将
this.didMount=true
; 每次更新后都会调用componentDidUpdate,因此您必须检查:
!this.didUpdate=(this.didUpdate=true)

然后只检查这些属性

如果我正确理解了您的问题,那么您只需要在
componentDidMount
中包含一次初始值设定项。此函数仅在组件装入DOM时运行一次。刷新页面或导航到页面将导致此组件装载,从而触发初始值设定项功能。