我正在使用 React Router 4。
当我使用渲染参数 componentWillReceiveProps() 渲染组件时,它不会第一次触发,因此我需要单击两次才能将 Prop 发送到组件。
我这样渲染:
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
会被调用,当你对 props 值进行任何更改时,只有 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.
关于reactjs - React Router 4 - componentWillReceiveProps() 不触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43855879/