componentWillReceiveProps
の中に、どの小道具が変更されたかを確認する方法がありますか?componentWillReceivePropsでどのような小道具が変更されたか確認する方法
すなわち
componentWillReceiveProps (newProps) {
if(/* newProps.profileImage is different to previous props */) /* do stuff */
}
componentWillReceiveProps
の中に、どの小道具が変更されたかを確認する方法がありますか?componentWillReceivePropsでどのような小道具が変更されたか確認する方法
すなわち
componentWillReceiveProps (newProps) {
if(/* newProps.profileImage is different to previous props */) /* do stuff */
}
このlifecycle methodが呼び出された時点で、this.props
は小道具の前のセットを指します。
単一のプロパティーfoo
を新しいプロパティーと同じプロパティーで比較するには、newProps.foo
とthis.props.foo
を単に比較してください。あなたの例では:
componentWillReceiveProps (newProps) {
if(newProps.profileImage !== this.props.profileImage) /* do stuff */
}
それはcomponentWilReceiveProps
が呼ばれた後まで更新されませんので、あなたはまだ、this.props.profileImage
に比較することができます。例えば、docsに、本実施例が使用される:時点
componentWillReceiveProps: function(nextProps) {
this.setState({
likesIncreasing: nextProps.likeCount > this.props.likeCount
});
}
はい、特定の小道具が変更されたかどうか確認できます。 this.props
は、の前に小道具を参照しています。だから、例えば:
componentWillReceiveProps(newProps) {
if(newProps.profileImage != this.props.profileImage) {
/* do stuff */
}
}
注:小道具は必ずしもメソッドが呼び出されるたびに変更されませんので、変更支えるかを確認するためにテストの価値があります。
また、すべての小道具をループして、変更内容を確認することもできます。
componentWillReceiveProps(nextProps) {
for (const index in nextProps) {
if (nextProps[index] !== this.props[index]) {
console.log(index, this.props[index], '-->', nextProps[index]);
}
}
}