简体   繁体   English

React Redux和副作用说明

[英]React Redux and side effects explanation

I'm wrapping my forms to provide automatic validation (I don't want to use redux-form). 我包装表单以提供自动验证(我不想使用redux-form)。

I want to pass an onSubmit handler which must be fired after every input in form is validated: but how do I wait for form.valid property to turn into true && after wrapping submit was fired? 我想传递一个onSubmit处理函数,该函数必须在表单中的每个输入都经过验证后被触发:但是在包装提交被触发后,我如何等待form.valid属性变为true &&? I'm missing some logic here! 我在这里缺少一些逻辑!

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

Help! 救命!

Depending on your build config you could use Async/Await for your submit function. 根据您的构建配置,您可以将Async / Await用于submit功能。 Something like 就像是

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

And I think you will need to update your syncValidateForm slightly but this should put you on the right path. 而且我认为您将需要稍微更新syncValidateForm但这应该使您走上正确的道路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM