2017-02-15 4 views
0

Ich wickle meine Formulare zur automatischen Validierung (Ich möchte nicht Redux-Form verwenden).React Redux und Nebenwirkungen Erklärung

ich einen onSubmit Handler übergeben will, die nach jeder Eingabe in Form gebrannt werden muss validiert: aber wie ich warte auf form.valid Eigenschaft in wahre & & biegt nach dem Brennen wurde Einwickeln einreichen? Ich vermisse hier etwas Logik!

//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; 

Hilfe!

Antwort

0

Abhängig von Ihrer Build-Konfiguration können Sie Async/Await für Ihre submit Funktion verwenden. So etwas wie

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 
    } 
} 

Und ich denke, Sie werden Ihre syncValidateForm leicht aktualisieren müssen, aber dies sollte man auf dem richtigen Weg.