2017-02-15 13 views
0

自動検証を提供するために私のフォームをラッピングしています(私はredux-formを使いたくありません)。React Reduxと副作用の説明

私は、フォーム内のすべての入力が検証された後に解雇されなければならないのonSubmitハンドラを渡したい:しかしform.validプロパティは、提出が解雇されたラップの後に真& &に変身するためにどのように私は待っていますか?私はここにいくつかの論理が欠けている!

//in my Form.js hoc wrapping the forms 
@autobind 
submit(event) { 
    event.preventDefault(); 

    this.props.dispatch(syncValidateForm({ formName: this.props.formName, form: this.props.form })); 

    // ==> what should I do here? Here I know submit button was pressed but state is not updated yet with last dispatch result reduced! 
    //if(this.props.form.valid) 
    // this.props.submit(); 
} 

render() { 
    return (
     <form name={this.props.formName} onSubmit={this.submit}> 
      { this.props.children } 
     </form> 
    ); 

//action.js validating given input 
export const syncValidateInput = ({ formName, input, name, value }) => { 
    let errors = {<computed object with errors>};  
    return { type: INPUT_ERRORS, formName, input, name, value: errors }; 
}; 

//action.js validating every input in the form 
export const syncValidateForm = ({ formName, form }) => { 
    return dispatch => { 
     for(let name in form.inputs) { 
      let input = form.inputs[name]; 
      dispatch(syncValidateInput({ formName, input, name: input.name, value: input.value })); 
     } 
    }; 
}; 

//in my reducer I have 
    case INPUT_ERRORS: 
     let errors = value; 
     let valid = true; 
     let errorText = ''; 
     _.each(errors, (value, key) => { 
      if(value) { 
       valid = false; 
       errorText = `${errorText}${key}\n`; 
      } 
     }); 
     form.inputs[name].errors = errors; 
     form.inputs[name].valid = valid; 
     form.inputs[name].errorText = errorText; 

     _.each(form.inputs, (input) => form.valid = !!(form.valid && input.valid)); 

     return state; 

ヘルプ!

答えて

0

ビルドの設定によっては、submit機能でAsync/Awaitを使用できます。

async submit(event) { 
    event.preventDefault(); 

    const actionResponse = await this.props.dispatch(syncValidateForm({ formName: this.props.formName, form: this.props.form })); 

    if (actionResponse && this.props.form.valid) { //for example 
     // finish submission 
    } 
} 

ような何かそして私はあなたが少しあなたのsyncValidateFormを更新する必要がありますだと思うが、これは正しい道にあなたを置く必要があります。