Asked  7 Months ago    Answers:  5   Viewed   39 times

When is it important to pass props to super(), and why?

class MyComponent extends React.Component {
  constructor(props) {
    super(); // or super(props) ?
  }
}

 Answers

86

There is only one reason when one needs to pass props to super():

When you want to access this.props in constructor.

Passing:

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

        console.log(this.props)
        // -> { icon: 'home', … }
    }
}

Not passing:

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

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

        // Props parameter is still available
        console.log(props)
        // -> { icon: 'home', … }
    }

    render() {
        // No difference outside constructor
        console.log(this.props)
        // -> { icon: 'home', … }
    }
}

Note that passing or not passing props to super has no effect on later uses of this.props outside constructor. That is render, shouldComponentUpdate, or event handlers always have access to it.

This is explicitly said in one Sophie Alpert's answer to a similar question.


The documentation—State and Lifecycle, Adding Local State to a Class, point 2—recommends:

Class components should always call the base constructor with props.

However, no reason is provided. We can speculate it is either because of subclassing or for future compatibility.

(Thanks @MattBrowne for the link)

Tuesday, June 1, 2021
 
e_i_pi
answered 7 Months ago
50

Class Names

Firstly, if you're certain that you're extending from the correctly named class, e.g. React.Component, not React.component or React.createComponent, you may need to upgrade your React version. See answers below for more information on the classes to extend from.

Upgrade React

React has only supported ES6-style classes since version 0.13.0 (see their official blog post on the support introduction here.

Before that, when using:

class HelloMessage extends React.Component

you were attempting to use ES6 keywords (extends) to subclass from a class which wasn't defined using ES6 class. This was likely why you were running into strange behaviour with super definitions etc.

So, yes, TL;DR - update to React v0.13.x.

Circular Dependencies

This can also occur if you have circular import structure. One module importing another and the other way around. In this case you just need to refactor your code to avoid it. More info

Saturday, June 5, 2021
 
hohner
answered 7 Months ago
78

You are missing binding in your constructor, also you don't need to pass props if you are not using them in the constructor. Also you need to import { PropTypes } from 'react'

class SearchBar extends React.Component {

  constructor() {
    super();
    this.handler = this.handler.bind(this);
  }

  handler(e){
    this.props.filterUser(e.target.value);
  }

  render () {
    return (
      <div>
        <input type='text' className='from-control search-bar' placeholder='Search' onChange={this.handler} />
      </div>
    );
  }
}


export default class User extends React.Component {
  constructor() {
    super();
    this.filterUser = this.filterUser.bind(this);
    this.state = { name: '', age: '', filter: '' };
  } 

  filterUser(filterValue){
    this.setState({
      filter: filterValue
    });
  }

  render() {
    return ( 
      <div>
        <SearchBar filterUser={this.filterUser} />
        <span>Value: {this.state.filter}</span>
      </div>
    );
  }
}
Thursday, June 17, 2021
 
tadman
answered 6 Months ago
34

I did some mock testing to record the difference between Save() and Persist().

Sounds like both these methods behaves same when dealing with Transient Entity but differ when dealing with Detached Entity.

For the below example , take EmployeeVehicle as an Entity with PK as vehicleId which is a generated value and vehicleName as one of its property .

Example 1 : Dealing with Transient Object

                 Session session = factory.openSession();
                 session.beginTransaction();
                 EmployeeVehicle entity = new EmployeeVehicle();
                    entity.setVehicleName("Honda");
                 session.save(entity);
                 // session.persist(entity);
                session.getTransaction().commit();
                session.close();

Result : select nextval ('hibernate_sequence') // This is for vehicle Id generated : 36

insert into Employee_Vehicle ( Vehicle_Name, Vehicle_Id) values ( Honda, 36)

Repeat the same with using persist(entity) and will result the same with new Id ( say 37 , honda ) ;

Example 2 : Dealing with Detached Object

// Session 1 
            // Get the previously saved Vehicle Entity 
           Session session = factory.openSession();
            session.beginTransaction();
            EmployeeVehicle entity = (EmployeeVehicle)session.get(EmployeeVehicle.class, 36);
           session.close();

           // Session 2
           // Here in Session 2 , vehicle entity obtained in previous session is a detached object and now we will try to save / persist it 
         (i) Using Save() to persist a detached object 
           Session session2 = factory.openSession();
            session2.beginTransaction();
                    entity.setVehicleName("Toyota");
            session2.save(entity);
            session2.getTransaction().commit();
            session2.close();

Result : You might be expecting the Vehicle with id : 36 obtained in previous session is updated with name as "Toyota" . But what happens is that a new entity is saved in the DB with new Id generated for and Name as "Toyota"

         select nextval ('hibernate_sequence')
         insert into Employee_Vehicle ( Vehicle_Name, Vehicle_Id) values ( Toyota, 39)

         (ii) Using Persist()  to persist a detached object 

            // Session 1 
            Session session = factory.openSession();
    session.beginTransaction();
    EmployeeVehicle entity = EmployeeVehicle)session.get(EmployeeVehicle.class, 36);
    session.close();

// Session 2 // Here in Session 2 , vehicle entity obtained in previous session is a detached object and now we will try to save / persist it (i) Using persist() to persist a detached object

            Session session2 = factory.openSession();
    session2.beginTransaction();
            entity.setVehicleName("Toyota");
    session2.persist(entity);
    session2.getTransaction().commit();
    session2.close();

Result : Exception being thrown : detached entity passed to persist

So, it is always better to use Persist() rather than Save() as save has to be carefully used when dealing with session and transcation .

Tuesday, July 20, 2021
 
Fredy
answered 5 Months ago
70

There are two major releases of react navigation, react-navigation-v1 and react-navigation-v2

When react-navigation loads up a navigator e.g TabNavigator, it tries to render all the screens inside that navigator.

For react-navigation-v1: When the TabNavigator is mounted on the screen, It tries to push all the screens/components configured inside itself at once to the UI. So to avoid this behavior, in the TabNavigator options, lazyLoad: true or lazy: true is passed, so the Screens/Components can be rendered as required.

Until react-navigation 1.0.0-beta9, lazyLoad: true was used, but since it is stable now, lazy: true is used.

For react-navigation-v2: TabNavigator and createTabNavigator are deprecated, you will always get that yellow screen error, so use createBottomTabNavigator and/or createMaterialTopTabNavigator . The lazy option works with TabNavigator and createTabNavigator, createBottomTabNavigator has lazyLoading option built in, but createMaterialTopTabNavigator seems to buggy, the lazy option does not work.

I hope this answers your question.

Thursday, September 2, 2021
 
Wilk
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share