我正在阅读 React facebook 的文档和 there据记载
Invoked when a component is receiving new props. This method is not called for the initial render.
但稍后在 this链接,已经解释过即使 props 相同也会调用此方法,因为 props 可以是引用,而这些引用处的数据可能不同。
所以,我的问题是是否每次我们收到新 Prop 时都会调用它。
最佳答案
初始渲染意味着当你的组件第一次加载它所拥有的任何数据时。 例如:
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>}
)
}
子组件:
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
方法并更新子组件状态。
注意:componentWillReceiveProps
不检查 props 的内部值。这意味着即使以前和当前的 Prop 相同,它也会起作用。因此答案是是。每次从父级接收到新 Prop 时,它都会被调用。
关于html - componentWillRecieveProps 会在每次收到 props 时运行吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36011875/