我正在使用 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 - 需要单击 LINK 两次才能将 props 传递给组件 https://stackoverflow.com/questions/43814173/react-router-need-to-click-link-twice-to-pass-props-to-component
我认为原因很简单,根据DOC https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops:
React 在期间不会使用初始 props 调用 componentWillReceiveProps
安装。仅当某些组件的 props 可能时,它才会调用此方法
更新。在已安装的组件接收新的 props 之前调用 componentWillReceiveProps() 。
componentWillReceiveProps
第一次渲染组件时不会被调用,当时componentDidMount
被调用,当你对 props 值进行任何更改时,只有componentWillReceiveProps
会被触发。所以第一次如果你想做一些计算就这样做componentDidMount
方法,像这样:
componentDidMount(){
console.log('props values', this.props); //it will print the props values
}
componentWillReceiveProps
是更新生命周期方法而不是安装方法。
安装方法:
当组件的实例被调用时,这些方法被调用
创建并插入到 DOM 中。
更新方法:
更新可能是由 props 或 state 的更改引起的。这些方法
当组件被重新渲染时被调用。
检查 Mounting 和 Updating 生命周期方法之间的区别。 https://facebook.github.io/react/docs/react-component.html#the-component-lifecycle
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)