gpt4 book ai didi

Typescript:如何键入处理异步操作的自定义 redux 中间件

转载 作者:行者123 更新时间:2023-12-05 04:44:37 26 4
gpt4 key购买 nike

我希望这个周末每个人都过得很好!

免责声明:我已经研究了一整天,只是在尝试了很多东西之后才来寻求帮助,我打开了 20 多个 StackOverflow 链接并通读了它们......

我有这个自定义的 redux 中间件,用于捕获失败的 promise 并为每个 promise 分配一个操作。

const errorMiddleware: Middleware =
({ dispatch }: MiddlewareAPI) =>
(next: Dispatch) =>
async (action: AnyAction) => {
const { meta, payload } = action;
const { withErrorHandler, defaultErrorCode } = meta;

const isPromise = getIsPromise(payload);

if (isPromise && withErrorHandler) {
return next(action)
.catch(errorHandler(defaultErrorCode))
.catch((handledError: ISystemError) =>
Promise.reject(
handledError.shouldSkipHandleError
? handledError
: dispatch(addError(handledError))
)
);
}

return next(action);
};

我要解决的问题是 async (action: AnyAction) => {

我收到一条错误消息说

Argument of type 'AsyncThunkAction<number, number, {}>' is not assignable to parameter of type 'AnyAction'.
Property 'type' is missing in type 'AsyncThunkAction<number, number, {}>' but required in type 'AnyAction'. TS2345

53 | <button
54 | className={styles.asyncButton}
> 55 | onClick={() => dispatch(incrementAsync(incrementValue))}
| ^
56 | >
57 | Add Async
58 | </button>

这是因为 incrementAsync 使用来自 '@reduxjs/toolkit' 的 createAsyncThunk;

export const incrementAsync = createAsyncThunk(
'counter/fetchCount',
async (amount: number) => {
const response = await fetchCount(amount);
// The value we return becomes the `fulfilled` action payload
return response.data;
}
);

所以我认为我需要将最后一个函数 ``async (action: AnyAction) => {` 类型的操作更改为其他类型,但我无法弄清楚,请问您的话对我有何启示?

如果有帮助,这里是 typescript playground 的链接

https://www.typescriptlang.org/play?#code/PTAEEsFsAcHsCcAuoDeoCCA7AnugxouLJqAL6gBm8skoARPAKYAmArgB50BQUcSqoAOaNk5KjXoAbWMwCGAZwAWdANw8YCZGjxNZiRunnZMeACqLWmANYAaUDsZ7GAZUng8jOwAVZ2abOZ8QmIySmpaAHIAASY2d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yPvIoCsqAAAGFAehQ4CSCZyspu1oCvgEUnSw9jBNC8zKvfVXDkVwOxzetrCICkmC22At6SAo8gAHLSow-woK8fim0yxN4AAQo7zvqjsLrELBbh4FY-t3deyU7mlkNMNDiBI3gQKZyaRKIAAaqL4vadtuSu6MiiNIrijUP0CtKxQaTSABio8mF1foPAghrUXoCwNROZ5qAES52MFTtXNq0bbydhz9TdgoNtERYVNsDIJ74CCJgsjrX0iuwPrQy+1qQ8j7mfwTzgl4REy1dFIReZINg4+j4w691-R8jyAqggIAkE-uPSeKNp6nlnlTBelN57gVXkideDtkBMAAI6sHALEIBitr6gLvu1B+RRTDOAAEwAGYAAsP1cgx12D9MhoAKSeXtpHYgT86EUMYRFIoeAPZ-x9o+f2gc+jyBDiUcOrDMDRzdqAVUP0fpcO4XHBOScUApxVOOScckC7Z1zvnEwWci6lzFideE0jPJMO4VY6xAA9dhRQfoADZFF2RRLQhxAB2Fxnl0A9GKIeexoAfoAA5vG8TmsAZBzskRAA

最佳答案

尝试一下

const errorMiddleware: Middleware<{}, unknown, ThunkDispatch<unknown, unknown, AnyAction>> =
({ dispatch }) =>
(next) =>
async (action) => {

无需在 = 的左侧输入内容 - 在一侧输入内容会转移到另一侧。

关于Typescript:如何键入处理异步操作的自定义 redux 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69330464/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com