首页 文章

反应状态变化不会让克隆儿童重新回归

提问于
浏览
1

我有一个有状态的组件,Form . 在构造函数中我创建状态,然后我迭代组件子 . 我克隆目标孩子并使用添加道具

React.cloneElement(x, {data: modelProperty});

其中modelProperty是一个对象,上面有一个this.state . 由于克隆,我最终得到了this.props.children的不同实例 . 因此,在渲染中,我渲染了我的新子集,这些子集已经用父对象this.state进行了装饰 .

我希望他能在国家和孩子之间 Build 一种约束,这样当国家改变时,受影响的孩子就会被重新渲染 . 但是,当父组件(Form)重新呈现时,受状态更改影响的子项不会重新呈现 .

这可能有点令人困惑所以我会发布一些代码 .

constructor(props) {
  super(props);

  this.state = {
    fields: props.fields,
    formIsValid: true
  };
  this.newChildren = decorateInputs(this.props.children, this.state.fields);
}

然后

const decorateInput = (children, fields) => {
  return React.Children.map(children, x => {
    if(!x.props){ return x; }
    if (x.props.frfProperty) {
      var field = fields.filter(f => f.name === x.props.frfProperty)[0];
      if (!field) {
        throw new Error(`No property on model with name: ${x.frfProperty}!`)
      }
      return React.cloneElement(x, {data: field});
    }

    var clonedItems = decorateInput(x.props.children, fields);
    return React.cloneElement(x, {children: clonedItems});
  })
};

export default decorateInput;

然后

render() {
  return (<form onSubmit={this.onSubmitHandler.bind(this)} >
    {this.newChildren}
  </form>)
}

现在一个快速解决方法是在render方法中进行修饰,但这会再次呈现所有子组件,而不仅仅是状态发生变化的组件 .

我的基本问题是为什么克隆儿童的重新渲染行为被破坏或不存在 .

最后,我知道还有其他模式可行 . 我的问题是关于这样做的机制 . 即我知道redux,我知道我可以为消费者提供自己的包装材料 . 试着想出这个 .

谢谢,R

1 回答

  • 1

    你提到的绑定并不是自动化的 .
    我认为将装饰调用放在 componentWillUpdate() 回调 as well 中应该足够了 .

    componentWillUpdate(nextProps, nextState){
     this.newChildren = decorateInputs(nextProps.children, nextState.fields);
    }
    

    了解更多关于compontent lifecycle.的信息

相关问题