React Router 4 - componentWillReceiveProps() 不会触发

IT技术 reactjs components react-router render router
2021-04-28 13:46:12

我正在使用 React Router 4。

当我使用渲染参数 componentWillReceiveProps() 渲染组件时,它不会第一次触发,因此我需要单击两次才能将props发送到组件。

我这样渲染:

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

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

以下是详细说明:

React 路由器 - 需要单击 LINK 两次才能将props传递给组件

1个回答

我认为原因很简单,根据DOC

React 在挂载期间不会使用初始props调用 componentWillReceiveProps。仅当某些组件的 props 可能更新时才调用此方法。componentWillReceiveProps() 在挂载的组件接收新的 props 之前被调用。

componentWillReceiveProps第一次渲染组件时不会被调用,那时componentDidMount会被调用,当您对 props 值进行任何更改时,只会componentWillReceiveProps被触发。所以第一次如果你想在componentDidMount方法中做一些计算,像这样:

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

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

安装方法:

这些方法在创建组件实例并将其插入 DOM 时被调用。

更新方法:

更新可能由props或状态的更改引起。这些方法在组件被重新渲染时被调用。

检查 Mounting 和 Updateing 生命周期方法之间的区别。