Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router 4 - componentWillReceiveProps() doesn't fire

I'm using React Router 4.

When I render component with render parameter componentWillReceiveProps() it doesn't fire the fist time, so I need to click twice to sent props to the component.

I render like this:

const CartRoute = (props) => (<Cart itemsInCart = {this.state.itemsInCart} deleteItemFromCart = {this.deleteItemFromCart} {...props} />);
.....
  <Switch>
    .....
    <Route path="/cart" render={CartRoute} />
  </Switch>

Without Router (when all components are on the same page) it works ok.

Here is detailed description:

React router - Need to click LINK twice to pass props to Component

like image 425
alexfrize Avatar asked May 08 '17 19:05

alexfrize


1 Answers

I think Reason is simple one, As per DOC:

React doesn't call componentWillReceiveProps with initial props during mounting. It only calls this method if some of component's props may update. componentWillReceiveProps() is invoked before a mounted component receives new props.

componentWillReceiveProps will not get called when first time component get rendered, at that time componentDidMount get called, when you do any changes in props values then only componentWillReceiveProps will get triggered. So first time if you want to do some calculation do that in componentDidMount method, like this:

componentDidMount(){
   console.log('props values', this.props); //it will print the props values
}

componentWillReceiveProps is a Updating lifecycle method not Mounting method.

Mounting Methods:

These methods are called when an instance of a component is being created and inserted into the DOM.

Updating Methods:

An update can be caused by changes to props or state. These methods are called when a component is being re-rendered.

Check the difference between Mounting and Updating lifecycle method.

like image 121
Mayank Shukla Avatar answered Sep 26 '22 04:09

Mayank Shukla