When is it appropriate to use a constructor in REACT?

前端 未结 3 1875
长发绾君心
长发绾君心 2020-12-01 17:08

I understand the concept of constructors in OOP languages like C++. However, I am not entirely sure when to use a constructor in REACT. I do understand that JavaScript is ob

3条回答
  •  时光说笑
    2020-12-01 18:10

    A constructor function is NOT required at all.

    State initialization can be done directly in the body of a class and function can be assigned to properties as described below,

    Technically these are known as class properties, it may land up soon in native javascript, yet because almost all of us use Babel transpiler for React projects, we can use that syntax

    class Comp extends React.Component {
    /* 
     * generally we do not need to put the props in state, but even if we need to.
     * then it is accessible in this.props as shown below 
    **/
    state={ first: 1, second: this.props.second } 
    
    handler= (token) => {
     this.setState(prevState => ({first: prevState.first+1}));
    }
    
    render() {
     return 
    {this.state.first} and {this.state.second }
    } }

    Read more details about class properties and removing constructor from react class component over here. https://hackernoon.com/the-constructor-is-dead-long-live-the-constructor-c10871bea599

提交回复
热议问题