反应:丢失参考值

时间:2016-07-15 17:20:42

标签: reactjs refs

我正在使用两个组件,我正在使用这种模式:子组件应尽可能保持隔离 - 它正在处理自己的验证错误。父组件应检查具有子项之间依赖关系的错误。因此,就我而言:password字段和password confirmation字段。

这是我的代码:

a)SignUp(父母)

设置初始状态。

 constructor() {
     super();

     this.state = {
         isPasswordMatching: false
     };
 }

render()方法中,我输出了我的子组件。通过名为callback的道具,我通过绑定父级isPasswordMatching()来传播方法this。目标是可以在子组件中调用该方法。

<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.passwordthis.passwordConfirm),然后更新状态。请注意,此方法在child(password或passwordConfirm)内调用。

isPasswordMatching() {
    this.setState({
        isPasswordMatching: this.password.state.value === this.passwordConfirm.state.value
    });
}

b)TextInput(子)

设置初始状态。

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();
    }
}

问题

不知何故,我的裁判丢失了。情形:

  1. 父组件是渲染器
  2. 呈现子组件
  3. 我正在输入一个输入字段并退出(这会调用onBlur()方法) - 状态更新,子组件呈现
  4. componentDidUpdate()被调用,prevProp.callback()也被
  5. 转到isPasswordMatching()方法时,我输出this.passwordthis.passwordConfirm - 它们是具有预期参考值的对象。更新父组件的状态 - 组件将被渲染。
  6. 然后再次渲染所有子项,更新组件,调用回调,但此时this.passwordthis.passwordConfirmnull
  7. 我不知道为什么引用有点丢失。我应该采取不同的做法吗? 提前谢谢。

2 个答案:

答案 0 :(得分:12)

请参阅react documentation here,并提供重要警告,并告知何时使用或不使用参考号。

  

请注意,在卸载引用的组件时,每当ref更改时,将使用null作为参数调用旧的ref。这可以防止在存储实例的情况下发生内存泄漏,如第二个示例中所示。另请注意,当使用内联函数表达式编写refs时,如此处的示例中所示,每次更新时,React都会看到不同的函数对象,在使用组件实例调用之前,ref将立即调用null。

答案 1 :(得分:5)

我不确定这是否可以解答@ be-codified的问题,但我发现这个问题也遇到了类似的问题。在我的情况下,事实证明它是由于使用功能组件。

https://reactjs.org/docs/refs-and-the-dom.html#refs-and-functional-components

  

参考和功能组件   您可能不会在功能组件上使用ref属性,因为它们不会   如果需要引用它,则应该将组件转换为类,就像您需要生命周期方法或状态时一样。   但是,只要引用DOM元素或类组件,就可以在函数组件中使用ref属性

文档说明了如果您控制了您尝试渲染的组件,应该采取什么措施来解决问题。

但在我的情况下,该组件来自第三方库。因此,简单地包装组件工作正常。

<强>工作

<div ref={element => this.elementName = element}>
    <FunctionalComponent />
</div>

不工作
将this.elementName设置为null

<FunctionalComponent ref={element => this.elementName = element} />

希望这有助于任何人像我一样找到这个问题。