Ala*_*ira 5 typescript reactjs 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 });
});
};
};
Run Code Online (Sandbox Code Playgroud)
我之前在没有使用该操作时让它工作过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 });
});
};
};
Run Code Online (Sandbox Code Playgroud)
但是一旦我添加了 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 });
});
};
};
Run Code Online (Sandbox Code Playgroud)
这样做,我收到一个错误: 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>'
一个朋友帮我回答了这个问题。这是正确的做法:
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 });
});
};
};
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是我的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,
};
Run Code Online (Sandbox Code Playgroud)
但接口需要是:
interface MapDispatchToPropsInterface {
saveValue : (saveDetails: CheckedVisit) => (dispatch: Dispatch<SaveValue>, getState: () => StoreState) => void;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5695 次 |
| 最近记录: |