When do I need to pass prop to the constructor of the reacting component using super (props)?

Many times we send details in the constructor, but we never use this.props anywhere in the constructor, so why do we need to pass this and when do we need to.

 class App extends React.Component {

      constructor(props) {
        super(props);    // When do we need to send props to the constructor
        this.state = {
           data: 'Initial data...'
        }
        this.updateState = this.updateState.bind(this);
      };

      updateState(e) {
          this.setState({data: e.target.value});
      }

      render() {
        return (
           <div>
             <input type = "text" value = {this.state.data} 
              onChange = {this.updateState} />
             <h4>{this.state.data}</h4>
          </div>
        );
      }

   }
+4
source share
1 answer

The details are not really needed by the designer React.Component. You can write this code and everything works fine:

constructor() {
    super();
    this.state = {
       data: 'Initial data...'
    };
    this.updateState = this.updateState.bind(this);
  };

, , React. React.Component this.props, . props , - -

babel, :

class MyComponent extends React.Component {
    state = { data: "initial data" };

    updateState = (arg1, arg2) => { ... };

    // instead of:
    // updateState(arg1, arg2) { ... }

}
+5

Source: https://habr.com/ru/post/1648811/


All Articles