reactjs - React Router 4 - componentWillReceiveProps() 不触发

标签 reactjs components react-router render router

我正在使用 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/

相关文章:

reactjs - 从 react typescript 中的对象数组中获取所有值

javascript - Flickr 使用什么来绘制图表?

javascript - 一个列表项而不是所有列表项的 ReactJS 悬停/鼠标悬停效果

javascript - ReactJS 几个css文件

express - 使用react-router和expressroutes.js有什么区别

javascript - 循环数组内的数字 - React

reactjs - 拉动 ScrollView 以显示 View - React Native

reactjs - 满足条件时,如何停止在 refetchInterval 上运行的 react 查询 useQuery?

angular - 如何在 Angular 2 中的模块之间共享组件?

nginx try_files 不起作用?