reac——父组件向子组件传递值,子组件何时能同步获得父组件改变后的值

//这里是父组件的代码:
export default class HeaderCom_son extends React.Component { constructor(props) { super(props) this.state = { counter: 0, } this.x = 0; this.y = 0; } componentWillMount() { this.timer = setInterval(function () { this.x++; this.setState({ counter: this.state.counter + 1 }) this.setState }.bind(this), 1000); this.pp = null; this.init(); } init() { this.pp = this.x} y={this.y} counter={this.state.counter}/>  //这个this.pp仅运行一次,所以就是仅赋值一次
 } render() { 
  
this.y++;
  return (
  

    
这是HeaderCom_son
    ====================
    

说明:this.x和this.state.counter都是在一个定义在componentWillMount内的计时器里实现自增


    

this.state.counter:{this.state.counter}

this.x:{this.x}


    ====================  
    

说明:this.y是定义在render方法里实现自增


    

this.y:{this.y}


    

下面是三个:HeaderCom_son_son组件


   {this.pp}  {/* 这个结果永远是初始值0,0,0不会变 */}
   this
.x} y={this.y} counter={this.state.counter}/>  {/* 这个结果是:子组件的props属性会实时改变,所以能同步获取父组件的改变 */}
     {/* 这个结果是当然页不会变 */}
  
);
  }
}

 

//这里是子组件的代码
import React from 'react'; export default class HeaderCom_son_son extends React.Component { render() { return(
我是HeaderCom_son_son
{this.props.x}
{this.props.y}
{this.props.counter}
); } }

 

运行293秒后的结果如下图所示:

reac——父组件向子组件传递值,子组件何时能同步获得父组件改变后的值_第1张图片

小总结:

  1、this.pp =   

    这个this.pp仅运行一次,所以就是仅赋值一次,并且我发现,this.pp.props和子元素的this.props显示是相同的,还有,即使运行时“等号”右侧的值是对象,this.pp.props的属性值仍是简单数据类型,

    所以,如果这个this.pp仅运行一次后期,无论this.pp.props内的属性再如何改变,都不会再传递到子组件上!

  2  {/* 这个结果是:子组件的props属性会实时改变,所以能同步获取父组件的改变 */}

    这个组件的属性都所以能够实时更新,是因为:它在render()方法里,而我们每次只要运行了setState更改都会重新运行render()方法,所以会重新运行:

    ,

    也就会重新赋值,所以能实现实时传递给子组件;

    但是,如果我们每次更新的并不是state,而仅仅更新其他值,如仅更新this.x,那么这个更新也不能同步传递给子组件,因为不会重新运行render(),也就不会重新赋值;

 

  最后的总结:

  归根结底,要判断子组件能否同步获得父组件传递过来的值,就是看父组件更新时,是否会重新运行传递给子组件属性的那句代码;

 

  

转载于:https://www.cnblogs.com/zhilingege/p/7434875.html

你可能感兴趣的:(reac——父组件向子组件传递值,子组件何时能同步获得父组件改变后的值)