【问题标题】:What is the difference between ComponentWillMount and ComponentDidMount in React JS?React JS 中的 ComponentWillMount 和 ComponentDidMount 有什么区别?
【发布时间】:2018-10-15 14:09:16
【问题描述】:

需要了解 ReactJs 中这两个 func 的区别。 ComponentWillMount(){} VS ComponentDidMount(){}

【问题讨论】:

标签: reactjs


【解决方案1】:

componentWillMount() 在第一次渲染之前被调用,而 componentDidMount() 在第一次渲染之后被调用。这两个组件只被调用一次

请注意,最新的 React 版本 v16 已弃用 componentWillMount()

【讨论】:

  • Constructer 和 ComponentWillMount 是否相同?
  • 构造函数基本上是初始化状态和做函数绑定。 componentWillMount 几乎相同,但我们不经常使用这种方法。因为我们在构造函数中进行所有初始化,所以建议在 componentWillMount
  • 好的。知道了。非常感谢
【解决方案2】:

讨论最多的话题仍在解释我的理解。 ComponentWillMount 顾名思义,在渲染之前执行 ComponentAfterMount 在渲染之前执行,一旦组件按照名称显示在屏幕上。

查看示例中的控制台日志

class App extends React.Component {
  componentWillMount(){
     console.log("console loging before component will mount");
  }
  componentDidMount(){
     console.log("console loging after mounting component");
  }
  render(){
    console.log("rendering component")
    return(
     <div> component</div>
    )
  }
}
ReactDOM.render(<App />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='root' />

【讨论】:

  • 您是说 ComponentWillMount 在渲染组件之前执行,而 ComponentDidMount 在渲染组件之后执行。对吗?
  • 是 componentDidMount 在组件渲染完成后执行
  • 知道了。非常感谢
【解决方案3】:

区别

componentDidMount()

  • 在安装组件后立即调用。
  • 每次挂载只调用一次,这是网络请求和订阅的好地方。
  • 不要在此处分配状态或调用 setState。

componentWillMount()

  • 在安装前调用。
  • 服务器渲染时调用的唯一方法
  • 应避免使用此方法(这是一种遗留方法,将在即将发布的 react 版本中删除)。

您应该避免使用 componentWillMount 并改用 componentDidMount 和构造函数 更多信息请查看官方react docs

【讨论】:

  • 知道了。非常感谢。
猜你喜欢
  • 2015-07-06
  • 2023-02-25
  • 1970-01-01
  • 2019-10-03
  • 2021-03-07
  • 1970-01-01
  • 2018-07-19
  • 1970-01-01
  • 2016-04-11
相关资源
最近更新 更多