在React中使用回调进行父子通信



我知道父母通过道具与孩子沟通,孩子通过调用道具函数与父母沟通。

我发现自己处于这样的情况:我有一个孩子的组成部分,我希望保持某种状态。该子级将调用一个prop函数,然后更新其状态。不过,有时我希望孩子只在家长完成处理后才更新其状态。父级可能会向服务器发出异步请求。在JavaScript中处理此问题的传统方法是使用回调。

不过,这感觉就像是父母与孩子沟通的另一个载体。我觉得这违反了React的数据流原则。我在这里的犹豫有道理吗?如果是这样的话,这就意味着将状态提升到父级。

这里有一个例子来说明我在说什么。我们有一个可切换/可折叠的窗体。ToggleableForm根据某些状态显示"+"或Form组件。当Form传播提交事件时,ToggleableForm将其代理到父级ToggleableFormContainer。我们想等到收到服务器的回复后再折叠表单。CCD_ 6将回调对象交给CCD_ 7。handleFormSubmit然后使用这些回调函数:

const ToggleableFormContainer = React.createClass({
  handleFormSubmit: function(cb) {
    $.ajax({
      url: self.props.url,
      dataType: 'json',
      cache: false,
      success: cb.onSuccess,
      error: cb.onError,
      },
    });
  },
  render: function() {
    return (
      <ToggleableForm onFormSubmit={this.handleFormSubmit} />
    );
  },
})
const ToggleableForm = React.createClass({
  getInitialState: function() {
    return {
      isOpen: false,
    };
  },
  handleOpen: function() {
    this.setState({ isOpen: true });
  },
  handleClose: function() {
    this.setState({ isOpen: false });
  },
  handleSubmit: function(data) {
    this.props.onFormSubmit(data, this.submitCallback);
  },
  submitCallback: {
    onSuccess: function() {
      this.setState({ isOpen: false });
    },
    onError: function() {
      // display error
    },
  },
  render: function() {
    if (this.state.isOpen) {
      return (
        <Form onFormSubmit={this.handleSubmit} onFormClose={this.handleClose} />
      );
    } else {
      return (
        <button onClick={this.handleOpen}>Open</button>
      );
    }
  },
});

谢谢!

将submitResult作为道具传递。最初设置为null。办理入住手续;

componentDidReceiveProps(nextProps) { 
  if (nextProps.submitResult) {
    if (nextProps.submitResult == "success") {
      this.setState({ isOpen: false });
    },
    else if (nextProps.submitResult == "error") {
      // display error
    },
  }
}

最新更新