ReactJS: Child component updates before parent state is set -
i have parent , child components state of child (openwhen shouldchildrender) controlled parent. i'm running issue child updated (receives props) before parent state updated after calling parent's setstate() child receives stale state until second pass through of flow. in second pass through child receives updated state , renders correctly.
parent:
opendeactivatewarning: function (resource) { this.setstate({ opendeactivatemodal: true, workingresource: resource }); console.log('this.state.opendeactivatemodal still false here', this.state); }, render: function () { return ( <modal openwhen={this.state.opendeactivatemodal} opencallback={this.opendeactivatewarning}> <p>some modal content</p> </modal> ) }
child:
componentwillreceiveprops: function () { console.log('this fired before parent state changes , openmodal not called'); if (this.props.openwhen) { this.openmodal(); } },
i know setstate() not result in state change under impression children still re-rendered after state changed. there more preferable way of accomplishing this?
you should use nextprops updated. this.props.openwhen
in componentwillreceiveprops
still old 1 when parent component updates it's state.
componentwillreceiveprops: function (nextprops) { console.log('this fired before parent state changes , openmodal not called'); if (nextprops.openwhen) { <-- updated props this.openmodal(); } }
Comments
Post a Comment