reactjs - React: Losing ref values -
i using 2 components , using pattern: child component should stay isolated can - handling own validation error. parent component should check errors have dependencies between children. so, in case: password
field , password confirmation
field.
here code:
a) signup (parent)
setting initial state.
constructor() { super(); this.state = { ispasswordmatching: false }; }
in render()
method outputting child component. through prop called callback
propagating method ispasswordmatching()
binding parent's this
. goal method can called within child component.
<textinput id={'password'} ref={(ref) => this.password = ref} callback={this.ispasswordmatching.bind(this)} // other unimportant props /> <textinput id={'passwordconfirm'} ref={(ref) => this.passwordconfirm = ref} ...
ispasswordmatching()
method checking if passwords match (through refs this.password
, this.passwordconfirm
) , updates state. please note method called inside child (password or passwordconfirm).
ispasswordmatching() { this.setstate({ ispasswordmatching: this.password.state.value === this.passwordconfirm.state.value }); }
b) textinput (child)
setting initial state.
constructor() { super(); this.state = { value: '', isvalid: false }; }
on blur validation done , state updated.
onblur(event) { // doing validation , preparing error messages this.setstate({ value: value, isvalid: this.error === null }); }
latest. callback prop called.
componentdidupdate(prevprops) { if (prevprops.id === 'password' || prevprops.id === 'passwordconfirm') { prevprops.callback(); } }
issue
somehow refs lost. scenario:
- parent component renderder
- child components rendered
- i entering 1 of input fields , out (this invokes
onblur()
method) - state gets updated, child component rendered componentdidupdate()
invoked ,prevprop.callback()
well- when going
ispasswordmatching()
method outputtingthis.password
,this.passwordconfirm
- objects expected values of reference. updating state of parent - component gets rendered. - then again children rendered, components updated, callback called time
this.password
,this.passwordconfirm
null
.
i have no idea why references kinda lost. should doing differently? thank in advance.
see react documentation here, important warnings , advise when use or not use refs.
note when referenced component unmounted , whenever ref changes, old ref called null argument. prevents memory leaks in case instance stored, in second example. note when writing refs inline function expressions in examples here, react sees different function object each time on every update, ref called null before it's called component instance.
Comments
Post a Comment