javascript - Update parent's state through callback prop from children (React.js) -
i have page.jsx using form.jsx component:
<form isvalid={this.enablebutton} isinvalid={this.disablebutton}> <input validation={{ presence: true }} /> </form>
the point is: form
needs check each input
validness proceed. achieve this, doing in form.jsx
:
// ... allinputsarevalid: function () { return _.all(this.state.inputsvalidation, function (inputsvalidation) { return inputsvalidation.error === false; }); } // ...
then, in render
method of form.jsx
:
if (this.allinputsarevalid()) { this.props.isvalid(); } else { this.props.isinvalid(); }
finally, methods enable
/disablebutton
(on form.jsx):
// ... enablebutton: function () { this.setstate({ cansubmit: true }); }, disablebutton: function () { this.setstate({ cansubmit: false }); } //...
changing state in these methods, console throws error:
uncaught error: invariant violation: setstate(...): cannot update during existing state transition (such within
render
). render methods should pure function of props , state.
why? how fix?
i assuming "page.jsx" contains methods "enablebutton" , "disablebutton".
while updating state have other state properties apart "cansubmit"? if have other state properties along "cansubmit" forcing them become undefined doing
this.setstate({ cansubmit: true );
so assuming there state property called "xyz" existed along "cansubmit" state property. update state below
this.setstate({ cansubmit: true, xyz:this.state.xyz );
or better try use react update addon update state. more find here https://facebook.github.io/react/docs/update.html
update
try below code in page.jsx file
shouldcomponentupdate(object nextprops, object nextstate){ if(this.state.cansubmit==nextstate.cansubmit){ return false } }
Comments
Post a Comment