【发布时间】:2016-11-19 00:06:31
【问题描述】:
我正在使用两个组件,并且我正在使用这种模式:子组件应尽可能保持隔离 - 它正在处理自己的验证错误。父组件应检查子组件之间存在依赖关系的错误。所以,就我而言:password 字段和password confirmation 字段。
这是我的代码:
a) 注册(父级)
设置初始状态。
constructor() {
super();
this.state = {
isPasswordMatching: false
};
}
在render() 方法中,我正在输出我的子组件。通过名为callback 的道具,我通过绑定父级的this 来传播方法isPasswordMatching()。目标是可以在子组件中调用方法。
<TextInput
id={'password'}
ref={(ref) => this.password = ref}
callback={this.isPasswordMatching.bind(this)}
// some other unimportant props
/>
<TextInput
id={'passwordConfirm'}
ref={(ref) => this.passwordConfirm = ref}
...
isPasswordMatching() 方法是检查密码是否匹配(通过引用 this.password 和 this.passwordConfirm)然后更新状态。请注意,此方法在子进程内部调用(密码或密码确认)。
isPasswordMatching() {
this.setState({
isPasswordMatching: this.password.state.value === this.passwordConfirm.state.value
});
}
b) 文本输入(子)
设置初始状态。
constructor() {
super();
this.state = {
value: '',
isValid: false
};
}
模糊验证已完成并更新状态。
onBlur(event) {
// doing validation and preparing error messages
this.setState({
value: value,
isValid: this.error === null
});
}
最新的。回调属性被调用。
componentDidUpdate(prevProps) {
if (prevProps.id === 'password' || prevProps.id === 'passwordConfirm') {
prevProps.callback();
}
}
问题
不知何故,我的裁判丢失了。场景:
- 父组件是渲染器
- 子组件被渲染
- 我正在输入一个输入字段并退出(这会调用
onBlur()方法)- 状态得到更新,子组件被渲染 -
componentDidUpdate()被调用,prevProp.callback()也被调用 - 当使用
isPasswordMatching()方法时,我输出this.password和this.passwordConfirm- 它们是具有预期参考值的对象。更新父组件的状态 - 组件被渲染。 - 然后再次渲染所有子级,更新组件,调用回调,但这次
this.password和this.passwordConfirm是null。
我不知道为什么引用会丢失。我应该做一些不同的事情吗? 提前谢谢你。
【问题讨论】: