简体   繁体   English

在React组件安装到DOM后触发了任何事件吗?

[英]Any event triggered after React component mounted in DOM?

If I try to do document.querySelector for an element inside the React component inside componentDidMount , it seems like it does not guarantee it ( componentDidMount ) gets called after its on the DOM. 如果我尝试做document.querySelector为内做出反应组件内部的元素componentDidMount ,现在看来似乎并不保证它( componentDidMount )其对DOM之后被调用。 The result is it cannot find the element 结果是找不到元素

Is there an event I should used instead if I want to access the DOM? 如果要访问DOM,是否应该使用某个事件代替? After its attached to the DOM? 将其附加到DOM之后?

As a workaround, I used setTimeout is there a better way? 解决方法是,我使用setTimeout有更好的方法吗?

Another approach is that in your componentDidMount method set some state change. 另一种方法是在您的componentDidMount方法中设置一些状态更改。 it makes an update on your component and call render method again with absolute mounted status. 它会在组件上进行更新,并以绝对安装状态再次调用render方法。

like this: 像这样:

componentDidMount(){
  this.setState({
    isMounted: true
  })
}

componentWillUpdate(nextProps, nextState){
  if(nextState.isMounted){
     // do something for your query selecting
  }
}

componentWillUnmount(){
  // do something else if you want
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM