如果我有一个初始化某些东西(如 jQuery 小部件)的方法,我如何确保初始化只被调用一次,但在刷新和导航到该页面而不刷新时被调用。我目前的做法如下:
// 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,例如。做了挂载,做了更新。 componentDidMount 只会被调用一次,所以你可以把 this.didMount = true
;
componentDidUpdate 每次更新后都会被调用,所以你必须检查: !this.didUpdate = (this.didUpdate = true);
然后只检查这些属性;
关于javascript - 确保在 componentDidUpdate() 和 componentDidMount() 中只运行一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37842200/