admin管理员组

文章数量:1023782

If you need to specify initial state in a class, I see people did this

class App extends React.Component {
   constructor() { super(); this.state = { user: [] } }
   render() {
      return <p>Hi</p>
   }
}

but what's wrong without a constructor?

class App extends React.Component {
   state = { user: [] }
   render() {
      return <p>Hi</p>
   }
}

If you need to specify initial state in a class, I see people did this

class App extends React.Component {
   constructor() { super(); this.state = { user: [] } }
   render() {
      return <p>Hi</p>
   }
}

but what's wrong without a constructor?

class App extends React.Component {
   state = { user: [] }
   render() {
      return <p>Hi</p>
   }
}
Share Improve this question asked Dec 15, 2017 at 16:30 Jenny MokJenny Mok 2,80410 gold badges33 silver badges62 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

but what's wrong without a constructor?

There is nothing "wrong" with it. But it uses the class properties proposal which is not officially part of the language yet (since you tagged the question with ecmascript-6: It is not part of ES6). So you have to correctly configure your build system to be able to use it (in addition to what's needed for JSX).

If you need to specify initial state in a class, I see people did this

class App extends React.Component {
   constructor() { super(); this.state = { user: [] } }
   render() {
      return <p>Hi</p>
   }
}

but what's wrong without a constructor?

class App extends React.Component {
   state = { user: [] }
   render() {
      return <p>Hi</p>
   }
}

If you need to specify initial state in a class, I see people did this

class App extends React.Component {
   constructor() { super(); this.state = { user: [] } }
   render() {
      return <p>Hi</p>
   }
}

but what's wrong without a constructor?

class App extends React.Component {
   state = { user: [] }
   render() {
      return <p>Hi</p>
   }
}
Share Improve this question asked Dec 15, 2017 at 16:30 Jenny MokJenny Mok 2,80410 gold badges33 silver badges62 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 11

but what's wrong without a constructor?

There is nothing "wrong" with it. But it uses the class properties proposal which is not officially part of the language yet (since you tagged the question with ecmascript-6: It is not part of ES6). So you have to correctly configure your build system to be able to use it (in addition to what's needed for JSX).

本文标签: javascriptunnecessary constructor in react classStack Overflow