React Router 4 - componentWillReceiveProps() doesn't fire

女生的网名这么多〃 提交于 2019-12-10 14:06:09

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/43855879/react-router-4-componentwillreceiveprops-doesnt-fire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!