我读阵营Facebook的文件和有它被写
组件接收新道具时调用。初始渲染不调用此方法。
但是在此链接的后面,已经解释了,即使道具相同,也将调用此方法,因为道具可以是引用,并且这些引用处的数据可能不同。
所以,我的问题是,每当我们收到新的道具时,它是否被调用。
初始渲染表示第一次使用组件中的任何数据加载组件时。例如:
Parent constructor() { super(); this.state = { viewData:undefined, }; componentDidMount(){ let myData = yourStore.getData(); this.setState({viewData:myData}) } updateView(){ let myData = yourStore.getData(); this.setState({viewData:myData}) } render() { return( <div> { this.state.viewData && this.state.viewData.map(function (obj, index) { return <childComponenet data={obj} key={index}/> }) } </div> <button onClick={this.updateView.bind(this)>Update</button>} ) }
ChildComponent:
constructor() { super(); this.state = { childData:this.props.data } }; //componentDidMount(){ //this.setState({childData:this.props.data}) } componentWillReceiveProps(newProps){ this.setState({childData:newProps.data})//this method will not get called first time } render(){ return( <span>{this.state.childData}</span> ) }
构造函数仅初始化一次。因此,当第一次呈现子组件时,它将设置state变量。现在,当您单击父组件中的更新状态时,将state被更新,它将更新后的state形式传递props给子组件。在这种情况下,componentWillReceiveProps方法将被调用并更新子组件状态。
state
props
componentWillReceiveProps
注意:componentWillReceiveProps不检查道具的内部价值。这意味着即使以前的道具和当前的道具相同,它也会起作用。因此,答案是 肯定的 。每当它从父母那里收到新的道具时,它将被调用。