1

Preface: I'm a rails developer that is familiar enough with Javascript to write basic things but my overall understanding of the frameworks in question react + react-redux + redux-form may be insufficient. I'm still working on that.

Task to Accomplish: I'm trying to implement a multiple page form using redux-form. I have the multiple page form working. I now need to post all three pages of the wizard's values in one XHR request.

The Problem: I'm following the example of the multipage Wizard form in the redux-form documentation: http://redux-form.com/4.2.0/#/examples/wizard?_k=h898k7

However, I don't seem to understand where an XHR request should be handled. This may be a fundamental misunderstanding of react and react-redux. I see they have an onSubmit function passed to each wizard page from WizardForm.js parent component, but I don't think I understand where WizardForm.js is getting that onSubmit function nor what the shape of that function would be if the goal is to accomplish an XHR PUT request on WizardFormThirdPage.js.

Also, though the goal of the form submission isn't (yet) to change any of the redux store's state, would it be rational to make an action that does the XHR when something is dispatched like 'SUBMIT_FORM'?

4

1 回答 1

2

当像“SUBMIT_FORM”这样发送某些东西时,做出一个执行 XHR 的操作是否合理?

绝对地!操作不必返回像 之类的对象{ type: FOO },它们也可以返回函数,当你想做 XHR 的事情时,这会让生活变得更轻松:http ://redux.js.org/docs/advanced/AsyncActions.html 。

至于您问题的其他部分,如果您不遵循异步操作路径,理论上 ajax 请求几乎可以在任何地方完成,但在组件层次结构中有意义的最高中心点通常更好。在您的情况下,WizardForm 组件没有理由不处理这个问题。WizardForm 还必须跟踪在三个页面中输入的值,除非...

如果您已经使用 Redux 来存储该数据,那么您就可以开始了- 只需使用存储,否则您必须将 WizardForm 中的函数传递给负责更新 WizardForm 本地状态的每个单独页面。

在下面的伪示例中,您可以看到我如何将函数 onSetPageValue 传递给向导页面,并使用它来更改 WizardForm 的状态。在您发布的示例中,WizardForm 从链中更高的位置获取此函数,但原理是相同的,这个概念是 React 的基础。

class WizardForm extends React.Component{
  constructor(props){
    super(props);
    this.onHandleSubmit = this.onHandleSubmit.bind(this);
    this.onSetPageValue = this.onSetPageValue.bind(this);
    this.state = {
      pageValues: {
        1: '',
        2: ''
      }
    }
  }
  onHandleSubmit () {
    /* Do all xhr stuff, update state/store/whatever fits your application */
  }
  onSetPageValue(page, value){
    this.setState({
      pageValues: Object.assign({}, this.state.pageValues, {[page]:value})
    });
  }
  render(){
    return (
      <div>
        <WizardPage1 onSetPageValue={this.onSetPageValue}/>
        <button onClick={this.onHandleSubmit}>Submit</button>
      </div>
    )
  }
}

class WizardPage1 extends React.Component {
  render(){
    return (
      <button onClick={() => {this.props.onSetPageValue(1, 'Foo!')}}>Trigger onSetPageValue</button>
    );
  }
}
于 2016-03-25T00:14:20.570 回答