React, why use props in the constructor?

2

Hello, I have a question about reactjs, why should I use props inside the constructor and the props?

constructor(props){super(props)}

Why do not you use props in the constructor? Why not use props? Why use super?

Thanks for the help.

    
asked by anonymous 29.12.2018 / 19:11

1 answer

0
  

Why use super?

The super keyword is used to access the parent object of an object, in other cases it is used to access the parent class of a class.

When used in the constructor of a class, super must be used only once, and before the this keyword can be used.

  

Why use props in the constructor?

It only makes sense to use it in the constructor if you want to initialize the props-based state. Or if you want to use some past method via props .

Example:

class Pai extends React.Component {
  render() {
    return (
      <div>
        <Filho num={0} />
        <Filho num={10} />
        <Filho num={20} />
      </div>
    );
  };
}

class Filho extends React.Component {
  constructor(props) {
    super();

    this.state = {
      num: props.num,
    };
  };

  handleClick = () => {
    const {num} = this.state;
    this.setState({ num: num + 1});
  };

  render() {
    const { num } = this.state;

    return (
      <div>
        num = {num}
        <button
          onClick={this.handleClick} 
        >
          +
        </button>
      </div>
    );
  };
}
Codepen demo [https://codepen.io/rodamaral/pen/WLgraL]
  

Why not use props?

You can use super() or super(props) . The only difference is that using super(props) will cause this.props to be equal to props .

    
09.01.2019 / 22:06