使用dispatch和getState

时间:2018-06-11 09:06:52

标签: reactjs typescript redux redux-thunk

我正在努力弄清楚我的行动的返回类型应该是什么。在我使用any时,一切正常,但我正在努力避免使用any

export const saveValue = (value: number): any => {
    return (dispatch: Dispatch<SaveValue>, getState: () => State): void => {
        axios.post('www.exampleurl.com', value)
            .then((response) => {
                const someValueFromState = getState().stateValue;
                const payload = {...response, someValueFromState}
                dispatch({ type: constants.SAVE_VALUE, payload });
            });
    };
};

我在操作未使用getState()之前让它工作,它看起来像这样,返回Dispatch<SaveValue>

export const saveValue = (value: number): Dispatch<SaveValue> => {
    return (dispatch: Dispatch<SaveValue>): void => {
        axios.post('www.exampleurl.com', value)
            .then((response) => {
                dispatch({ type: constants.SAVE_VALUE, response });
            });
    };
};

但是一旦我添加了getState,我不知道该怎么做了。我试图将返回值放在变量中,并且可以看到我创建的对象是const myAttempt: (dispatch: Dispatch<SaveValue>, getState: () => State) => void但是当我尝试使用它时,它不起作用:

export const saveValue = (value: number): (dispatch: Dispatch<SaveValue>, getState: () => StoreState) => void => {
    return (dispatch: Dispatch<SaveValue>, getState: () => State): void => {
        axios.post('www.exampleurl.com', value)
            .then((response) => {
                const someValueFromState = getState().stateValue;
                const payload = {...response, someValueFromState}
                dispatch({ type: constants.SAVE_VALUE, payload });
            });
    };
};

这样做,我收到错误:A function whose declared type is neither 'void' nor 'any' must return a value.

编辑:

只是要添加,我不能像以前一样返回Dispatch<SaveValue>,否则我会收到此错误:Type '(dispatch: Dispatch<SaveValue>, getState: () => State) => void' is not assignable to type 'Dispatch<SaveValue>'

1 个答案:

答案 0 :(得分:0)

一位朋友帮我解答了这个问题。这是正确的方法:

export const saveValue = (value: number): (dispatch: Dispatch<SaveValue>, getState: () => State): void => {
    return (dispatch: Dispatch<SaveValue>, getState: () => State): void => {
        axios.post('www.exampleurl.com', value)
            .then((response) => {
                const someValueFromState = getState().stateValue;
                const payload = {...response, someValueFromState}
                dispatch({ type: constants.SAVE_VALUE, payload });
            });
    };
};

我遇到的问题是我的mapDispatchToProps函数被明确输入并导致错误Type '(dispatch: Dispatch<SaveVisit>, getState: () => StoreState) => void' is not assignable to type 'Dispatch<SaveVisit>'。功能是:

interface MapDispatchToPropsInterface {
    saveValue : (value: number) => Dispatch<SaveValue>;
}

const mapDispatchToProps: MapDispatchToPropsInterface = {
    saveValue : ActionCreators.saveValue,
};

但界面必须是:

interface MapDispatchToPropsInterface {
    saveValue : (saveDetails: CheckedVisit) =>  (dispatch: Dispatch<SaveValue>, getState: () => StoreState) => void;
}