【问题标题】:Constructor vs componentWillMount构造函数与组件WillMount
【发布时间】:2018-07-30 07:01:59
【问题描述】:

在 ReactJs 中,我们可以使用 componentWillMount 来做什么,而我们不能通过构造函数来做到这一点?两者都在组件渲染之前调用一次。

import React from 'react';

class Display extends React.Component {
  constructor(props)
  {
    super(props)   
    console.log('Display.Constructor...')
    console.log(this.props)
  
  }


  componentWillMount(){
    console.log('Display.componentWillMount...')
    console.log(this.props)
  }

【问题讨论】:

标签: javascript reactjs react-native


【解决方案1】:

我相信从 React 17 开始,ComponentWillMount 必须以 UNSAFE_ 为前缀才能使用,并且不鼓励使用它。

我认为你在构造函数中唯一不能用ComponentWillMount 实现的事情是setState() 如果你的构造函数中的任何东西甚至在另一个组件中修改了状态,也会发出警告。

有一个线程 here 您可能对此主题感兴趣。

【讨论】:

  • setState 在 componentWillMount 中不起作用