反应路由器4-componentWillReceiveProps()不触发 [英] React Router 4 - componentWillReceiveProps() doesn't fire

查看:295
本文介绍了反应路由器4-componentWillReceiveProps()不触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React Router 4。

I'm using React Router 4.

当我使用渲染参数componentWillReceiveProps()渲染组件时,它不会触发第一时间,因此我需要单击

When I render component with render parameter componentWillReceiveProps() it doesn't fire the fist time, so I need to click twice to sent props to the component.

我这样渲染:

const CartRoute = (props) => (<Cart itemsInCart = {this.state.itemsInCart} deleteItemFromCart = {this.deleteItemFromCart} {...props} />);
.....
  <Switch>
    .....
    <Route path="/cart" render={CartRoute} />
  </Switch>

没有路由器(当所有组件都在同一页面上时)就可以正常工作。

Without Router (when all components are on the same page) it works ok.

这里是详细说明:

React router - Need to click LINK twice to pass props to Component

推荐答案

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

I think Reason is simple one, As per DOC:



安装期间,React不会使用初始道具调用componentWillReceiveProps。仅当某些组件的道具可以
更新时,才会调用此方法。在已安装的组件接收新道具之前,将调用componentWillReceiveProps()。

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 被调用时,当您对prop值进行任何更改时,只有 componentWillReceiveProps 会被触发。因此,第一次,如果您想进行一些计算,请使用 componentDidMount 方法,例如:

componentWillReceiveProps will not get called when first time component get rendered, at that time componentDidMount get called, when you do any changes in props values then only componentWillReceiveProps will get triggered. So first time if you want to do some calculation do that in componentDidMount method, like this:

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

componentWillReceiveProps 是更新生命周期方法,而不是安装方法。

componentWillReceiveProps is a Updating lifecycle method not Mounting method.

安装方法:


在创建组件的实例
并将其插入DOM时将调用这些方法。

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.

检查安装和更新生命周期方法之间的区别。

这篇关于反应路由器4-componentWillReceiveProps()不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆