React Redux和副作用解释

时间:2017-02-15 22:20:18

标签: reactjs redux react-redux

我正在打包表单以提供自动验证(我不想使用redux-form)。

我想传递一个onSubmit处理程序,它必须在表单中的每个输入都被验证后触发:但我如何等待form.valid属性转为true&&包装提交被解雇后?我在这里错过了一些逻辑!

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

帮助!

1 个答案:

答案 0 :(得分:0)

根据您的构建配置,您可以使用Async / Await作为submit功能。像

这样的东西
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,但这应该会让您走上正确的道路。