1

鉴于没有太多关于此的示例,我会尽可能地关注文档,但验证不是被动的。

我声明了一个模式:

import { Tracker } from 'meteor/tracker';
import SimpleSchema from 'simpl-schema';

export const modelSchema = new SimpleSchema({
  foo: { 
    type: String,
    custom() {
      setTimeout(() => {
        this.addValidationErrors([{ name: 'foo', type: 'notUnique' }]);
      }, 100);  // simulate async
      return false;
    }
  }
}, {
  tracker: Tracker
});

然后我在我的组件中使用这个模式:

export default class InventoryItemForm extends TrackerReact(Component) {

  constructor(props) {
    super(props);

    this.validation = modelSchema.newContext();
    this.state = {
      isValid: this.validation.isValid()
    };
  }

  ...

  render() {
    ...
    const errors = this.validation._validationErrors;

    return (
      ...
    )
  }
}

因此,每当我尝试 validate 时foo,都会调用异步的自定义函数,并调用正确的函数,但是当应该为 falseaddValidationErrors时,组件永远不会重新渲染。this.validation.isValid()

我错过了什么?

4

1 回答 1

2

您的代码中实际上有两个错误。首先this.addValidationErrors不能在自定义验证中异步使用,因为它没有引用正确的验证上下文。其次,TrackerReact仅在函数内部注册响应式数据源(例如.isValidrender,因此仅在其中访问是不够的_validationErrors。因此,要使其正常工作,您需要使用命名的验证上下文,并isValid像这样调用渲染函数(或由它调用的其他函数):

在验证中

custom() {
  setTimeout(() => {
    modelSchema.namedContext().addValidationErrors([
      { name: 'foo', type: 'notUnique' }
    ]);
  }, 100);
}

组件

export default class InventoryItemForm extends TrackerReact(Component) {
  constructor(props) {
    super(props);

    this.validation = modelSchema.namedContext();
  }

  render() {
    let errors = [];
    if (!this.validation.isValid()) {
      errors = this.validation._validationErrors;
    }

    return (
      ...
    )
  }
}

在此处查看有关异步验证的更多信息。

于 2016-09-01T12:28:44.447 回答