构造函数道具状态与简单状态

iRo*_*tia 4 javascript reactjs react-native

当我们可以简单地使用状态和创建对象而不是使用时,我开始学习 React constructor(props){ super(props)

现在,我看到许多图书馆仍在使用

class Master extends Component {
  constructor(props){
    super(props)
Run Code Online (Sandbox Code Playgroud)

所以我的第一个问题是使用constructor (props) super(props)然后设置状态是否有优势?而不是仅仅创建状态对象?

第二个问题,我想在我制作的本机应用程序中实现react-native-slowlog

在整个代码中,我state object直接创建了而不是使用构造函数。

react-native-slowlog的文档显示了这种使用方式

class Master extends Component {
  constructor(props){
    super(props)
    slowlog(this, /.*/)

    this.state = this.getDataSource(props)
    this.shouldComponentUpdate = shouldComponentUpdate.bind(this)
  }
...
}
Run Code Online (Sandbox Code Playgroud)

他们slowlog(this, /.*/)在构造函数内部调用 的地方,所以我的问题是我可以避免在这里使用构造函数吗?或者如果我在那里创建一个构造函数 slowlog(this, /.*/)然后在构造函数之外创建状态对象可以吗?

class Master extends Component {
  constructor(){
    super() 
    slowlog(this, /.*/)
  } 


  state = {
    searchCoin: false
  }
Run Code Online (Sandbox Code Playgroud)

Yic*_*aoz 5

  • 为什么使用constructor (props){}super(props)

唯一的原因是当你想访问this构造函数内部的React 源代码时

如果你通过:

class MyComponent extends React.Component {
     constructor(props) {
         super(props)

         console.log(this.props)
         // goood
     }
 }
Run Code Online (Sandbox Code Playgroud)

如果你没有通过但打电话给超级

 class MyComponent extends React.Component {
     constructor(props) {
         super()

         console.log(this.props)
         // -> undefined

         // Props parameter is still available
         console.log(props)
         // good
     }

     render() {
         // No difference outside constructor
         console.log(this.props)
         // good
     }
 }
Run Code Online (Sandbox Code Playgroud)

如果你不打电话

class MyComponent extends React.Component {
     constructor(props) {
           console.log(this)
         // undefined
     }
 }
Run Code Online (Sandbox Code Playgroud)

所以总而言之,这并不总是需要的。

  • 在构造函数中与外部设置状态

那只是语法糖,因此没有区别。

构造函数每个挂载只调用一次,所以你想做一些你不想在每次渲染时都做的事情。