如果条件,其他操作后Redux调用操作

xan*_*r27 4 javascript reactjs redux redux-thunk react-redux

我应该如何在redux中实现以下逻辑:有2个动作:sync和async.让我们说它的validate()和save().当用户单击validate()执行的按钮时,它会更改isValid状态存储中的某个变量.然后,如果isValid执行保存操作.

Ric*_*lly 5

有很多方法可以做你想做的事.但是,作为一般规则,不要在Redux中存储可以派生的任何内容.isValid可以通过在您的字段上运行验证来派生.而且,我不认为像更改的表单字段值这样的中间状态属于Redux.我将它们存储在React状态,直到它们被认为有效并提交.

正如Spooner在评论中提到的那样,你可以在thunk中调用同步动作.或者您可以访问thunk中的状态.

选项1

// Action Creator
export default function doSomething(isValid) {
    return (dispatch) => {

        dispatch(setValid(isValid));

        if (isValid) {
            return fetch() //... dispatch on success or failure
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

选项#2

// Component
dispatch(setValid(isValid));
dispatch(doSomething());

// Action Creator
export default function doSomething() {
    return (dispatch, getState) => {

        const isValid = getState().isValid;

        if (isValid) {
            return fetch() //... dispatch on success or failure
        }
    };
}
Run Code Online (Sandbox Code Playgroud)