Javascript 类似componentDidUpdate的事件,但仅触发一次
我有一些组件,当它们的数据到达并第一次呈现时,它们应该做一些工作,但不用于将来的重新呈现。例如:加载并呈现注释,现在为1。加载社交媒体库和2。加载一些谷歌分析 现在我是这样做的:Javascript 类似componentDidUpdate的事件,但仅触发一次,javascript,reactjs,Javascript,Reactjs,我有一些组件,当它们的数据到达并第一次呈现时,它们应该做一些工作,但不用于将来的重新呈现。例如:加载并呈现注释,现在为1。加载社交媒体库和2。加载一些谷歌分析 现在我是这样做的: componentDidUpdate: function (prevProps, prevState) { if (this.hasAlreadyUpdatedOnce) { // ... do some stuff... } else { // ... do some
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()
您是否尝试过在ajax调用完成后更新状态?
或者您可以为componentShouldUpdate返回false,一旦ajax调用承诺解决了call forceUpdate问题。我不能给您一个明确的答案,因为我不知道您的ajax调用是在父组件中还是在子组件中,但无论哪种方式,您都应该能够利用
shouldComponentUpdate()
来实现您的目标。如果您真的不想在ajax调用后更新组件,那么您可以执行以下操作:
shouldComponentUpdate(){
返回false;
}
当ajax调用返回时,只需运行
this.forceUpdate()
。返回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));
}
我们有一个很好的例子来说明如何使用
isMounted()
如果组件呈现到DOM中,则返回true,
否则就错了。您可以使用此方法来保护异步调用
到setState()
或forceUpdate()
示例
首先,在“getInitialState()”中初始化状态变量:
在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));
}
但是在
componentDidMount
上,我最初的ajax请求还没有发生,这意味着DOM在那里,但是是空的。我想要执行的操作要求DOM包含来自初始ajax请求的数据。或者我误解了什么?您应该将数据加载到父组件中,并将其作为道具传递进来,以便在装载数据时可以获得数据
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));
}