【问题标题】:React Router 4 - componentWillReceiveProps() doesn't fireReact Router 4 - componentWillReceiveProps() 不会触发
【发布时间】:2017-10-06 22:36:31
【问题描述】:

我正在使用 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 - Need to click LINK twice to pass props to Component

【问题讨论】:

    标签: reactjs components react-router render router


    【解决方案1】:

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

    React 不会在使用初始 props 调用 componentWillReceiveProps 安装。如果组件的某些道具可能会调用此方法 更新。 componentWillReceiveProps() 在挂载的组件收到新的 props 之前被调用。

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

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

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

    安装方法:

    当一个组件的实例正在被调用时,这些方法被调用 创建并插入到 DOM 中。

    更新方法:

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

    Check the difference between Mounting and Updating lifecycle method.

    【讨论】:

    • 是的,它有帮助。谢谢!
    • 被卡在这个问题上很久了。感谢您的信息!
    • @Jay,很高兴它帮助了你先生 :)
    猜你喜欢
    • 1970-01-01
    • 2017-10-21
    • 2018-01-02
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 2018-08-16
    相关资源
    最近更新 更多