React Router 4 - componentWillReceiveProps() 不触发

5

我正在使用React Router 4。

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

我这样渲染:

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

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

以下是详细描述:

React路由器-需要点击两次链接才能将属性传递给组件

1个回答

5
我认为原因很简单,根据文档
React在挂载过程中不会使用初始属性调用componentWillReceiveProps。只有在组件的某些属性可能更新时才会调用此方法。 componentWillReceiveProps()在已挂载的组件接收新属性之前被调用。
当组件首次渲染时,componentWillReceiveProps不会被调用,此时将调用componentDidMount。仅当您更改props值时,才会触发componentWillReceiveProps。因此,如果您想进行某些计算,请在componentDidMount方法中执行,像这样:
componentDidMount(){
   console.log('props values', this.props); //it will print the props values
}

componentWillReceiveProps是一个更新生命周期方法,而不是挂载方法。

挂载方法:

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

更新方法:

当props或state发生更改时会导致更新。在重新渲染组件时将调用这些方法。

请查看挂载和更新生命周期方法之间的区别。


是的,它有帮助。谢谢! - alexfrize
卡在这个问题上太久了,感谢提供的信息! - Jay
@Jay,很高兴能帮到您先生 :) - Mayank Shukla

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接