React Router 4 - componentWillReceiveProps() 不会触发 [英] React Router 4 - componentWillReceiveProps() doesn't fire

查看:37
本文介绍了React Router 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 路由器 - 需要点击 LINK 两次将 props 传递给组件

推荐答案

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

I think Reason is simple one, As per DOC:

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

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 方法中做一些计算,像这样:

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.

更新方法:

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

An update can be caused by changes to props or state. These methods are called when a component is being re-rendered.

检查 Mounting 和 Updating 生命周期方法的区别.

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

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