ale*_*ize 5 router components render reactjs react-router
我正在使用React Router 4。
当我使用渲染参数componentWillReceiveProps()渲染组件时,它不会触发第一时间,因此我需要单击两次以将道具发送到组件。
我这样渲染:
const CartRoute = (props) => (<Cart itemsInCart = {this.state.itemsInCart} deleteItemFromCart = {this.deleteItemFromCart} {...props} />);
.....
<Switch>
.....
<Route path="/cart" render={CartRoute} />
</Switch>
Run Code Online (Sandbox Code Playgroud)
如果没有路由器(当所有组件都在同一页面上时),它可以正常工作。
详细说明如下:
我认为原因很简单,根据DOC:
在安装过程中,React不会使用初始道具调用componentWillReceiveProps。仅当组件的某些道具可能更新时,才调用此方法。在已安装的组件接收新道具之前,将调用componentWillReceiveProps()。
componentWillReceiveProps在首次渲染组件时componentDidMount不会调用,在那时,当您对props值进行任何更改时,只会componentWillReceiveProps被触发。因此,第一次,如果您想进行一些计算,请在componentDidMount方法中执行以下操作:
componentDidMount(){
console.log('props values', this.props); //it will print the props values
}
Run Code Online (Sandbox Code Playgroud)
componentWillReceiveProps 是更新生命周期方法,而不是安装方法。
安装方法:
当创建组件实例并将其插入DOM时,将调用这些方法。
更新方法:
更新可能是由于道具或状态的更改引起的。重新渲染组件时将调用这些方法。
| 归档时间: |
|
| 查看次数: |
3401 次 |
| 最近记录: |