我有一些组件应该在它们的数据到达并首次呈现后立即做一些工作,但不会为将来的重新呈现做准备。例如:加载和呈现评论,现在 1. 加载社交媒体库和 2. 加载一些 Google Analytics。
现在我是这样做的:
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;
}
}
但我在问自己是否有比设置这样的属性更优雅的方法。
最佳答案
假设您正在响应状态更改,您应该将回调作为第二个参数传递给 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));
}
关于javascript - 类似 componentDidUpdate 的事件,但只触发一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28419276/