简体   繁体   English

当多个子代同时发送事件时,更新组件父代的反应状态

[英]Updating react state of a component-parent when several children sent events simultaneously

I'm using ReactJs with Redux. 我在Redux上使用ReactJs。

There is a parent component, which has several children. 有一个父组件,其中有几个子组件。 Children are just input elements with build-in validation. 子代只是具有内置验证的输入元素。

<ParamInput
  type="number"
  value={item.capacity}
  name="capacity"
  min="1"
  validators={[Validator.required]}
  onValidation={this.validate}
/>

I'd like the parent to be aware which of its children are invalid. 我希望父母知道哪个孩子无效。

For this each child can fire "onValidate" event, parent listens to this event and collects the validation data in his state. 为此,每个孩子都可以触发“ onValidate”事件,父母会监听此事件并收集其状态下的验证数据。 This works pretty good if the validate event fired by one child at a time. 如果validate事件一次由一个孩子触发,则效果很好。

However, once several children trigger this event at the same time, I run into a problem. 但是,一旦几个孩子同时触发此事件,我就会遇到问题。 For example, I run onValidation in componentDidMount of a child, to know validation information for an initial value. 例如,我在孩子的componentDidMount中运行onValidation,以了解初始值的验证信息。

Parent processes the event and updates its state: 父级处理事件并更新其状态:

  validate(isValid, propertyName) {
    const newValidityState = { ...this.state.validity, ...{[propertyName]: isValid} };
    this.setState({validity : newValidityState });
    }

The problem is in combination of following: 问题在于以下几点:

  1. 'validate' will be called for each child at the same time 将同时为每个孩子调用“验证”
  2. I amend the existing value of this.state.validity 我修改this.state.validity的现有值
  3. 'setState' does not happen immediately 'setState'不会立即发生

Thus, by the end the state will have data only about the last child which called 'onValidate', because at the time 'newValidityState' was created this.state.validity didn't get updates from other changes of state. 因此,到最后,状态将仅包含有关最后一个称为“ onValidate”的子级的数据,因为在创建“ newValidityState”时,this.state.validity并未从状态的其他更改中获取更新。

How can I overcome this? 我该如何克服? I'm aware that I can use promises for setState, but I don't see how I can apply them for this case. 我知道我可以对setState使用promise,但是我看不到如何在这种情况下应用它们。

Would be grateful for your suggestions. 非常感谢您的建议。

This may not be an ideal solution. 这可能不是理想的解决方案。 But give it a try. 但是尝试一下。 Instead of updating validity propery of state, state should have properties for each ParamInput for eg: validation_propertyName and its value should be boolean indicating validity. 除了应该更新状态的有效性属性,状态还应该为每个ParamInput具有属性,例如: validation_propertyName ,其值应为布尔值,指示有效性。

validate(isValid, propertyName) {
     this.setState({["validation_"+propertyName]: isValid });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM