React Router 4 - componentWillReceiveProps() 不触发

React Router 4 - componentWillReceiveProps() doesn't fire

我正在使用 React Router 4。

当我使用渲染参数 componentWillReceiveProps() 渲染组件时,它不会第一次触发,所以我需要点击两次才能将道具发送到组件。

我这样渲染:

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

没有路由器(当所有组件都在同一页上时)它工作正常。

详细说明如下:

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

我认为原因很简单,根据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 不会在第一次渲染组件时被调用,那时 componentDidMount 被调用,当你对道具值进行任何更改时,只有 componentWillReceiveProps 会被触发.所以第一次如果你想做一些计算在 componentDidMount 方法中做,像这样:

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

componentWillReceiveProps 是更新生命周期方法而不是安装方法。

安装方法:

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

更新方法:

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.