React Life cycle method behavior with the React Router

React Life cycle method behavior with the React Router
0.0 0

#1

Hi, just wondering if the life cycle methods behavior is different if they are inside the Route component. Tried to look through StackOverFlow but couldn’t find relevant info.

For instance I have this route:

<Route path="/basket" render={()=><Baskets test={“hi”} />}/>

I have tried to use several life cycle methods like “componentWillReceiveProps”, “componentDidUpdate” and “componentDidMount”. The only method works is “componentDidMount” but that triggers every time I navigate to the component.

The reason I am asking is because I need to pass some props to the component and use those props to update the state of Basket component. Your help is appreciated.


#2

It’s been a while since I’ve used React Router but passing props into the component should not be a problem with the code you posted. Just to make sure that I’m on the same page:

<Route path="/basket" render={()=><Baskets test={“hi”} />}/>
// Basket.js

class Basket extends React.Component {
  componentDidMount() {
    console.log(this.props.test); // "hi"
  }
}

I think the issue that you mentioned isn’t one with passing props but that props are only passed once when you navigate to the route related to that component. As such, and if I’m not mistaken, componentWillReceiveProps shouldn’t get called after the component is mounted because no more props are being passed into it. If no props and states have changed and that React doesn’t think a re-render needs to occur, then componentDidUpdate will also not get called.

I suspect that your problem could be solved be reorganising how props are being passed down (or perhaps use a state container like Redux if you are not already using one), but without seeing the rest of the code I can only speculate that you have a list of items that the user has picked on one or more pages and you want to pass them down to the <Baskets> component (inside which has multiple <Basket> components that is dynamically generated)—is that list of items currently stored as React states in another component and hence the issues you are having?

EDIT: fixed typos!