gpt4 book ai didi

reactjs - 如何使用Redux Toolkit(带有TypeScript)解决 'Property '类型中缺少 'AsyncThunkAction'类型的问题?

转载 作者:行者123 更新时间:2023-12-03 16:07:18 25 4
gpt4 key购买 nike

我正在将Redux Toolkit与下面的thunk/slice配合使用。我认为可以只在本地处理这些问题,而不是将错误设置为state,而只需等待解决笨拙的 promise using the example provided here即可。
我想我可以通过在状态中设置error来避免这样做,也许应该避免,但是我有点想了解我在哪里出错了。

Argument of type 'AsyncThunkAction<LoginResponse, LoginFormData, {}>' is not assignable to parameter of type 'Action<unknown>'.
Property 'type' is missing in type 'AsyncThunkAction<LoginResponse, LoginFormData, {}>' but required in type 'Action<unknown>'
resultAction传递给 match时出现错误:
enter image description here
const onSubmit = async (data: LoginFormData) => {
const resultAction = await dispatch(performLocalLogin(data));
if (performLocalLogin.fulfilled.match(resultAction)) {
unwrapResult(resultAction)
} else {
// resultAction.payload is not available either
}
};
重击:
export const performLocalLogin = createAsyncThunk(
'auth/performLocalLogin',
async (
data: LoginFormData,
{ dispatch, requestId, getState, rejectWithValue, signal, extra }
) => {
try {
const res = await api.auth.login(data);
const { token, rememberMe } = res;
dispatch(fetchUser(token, rememberMe));
return res;
} catch (err) {
const error: AxiosError<ApiErrorResponse> = err;
if (!error || !error.response) {
throw err;
}
return rejectWithValue(error.response.data);
}
}
);
片:
const authSlice = createSlice({
name: 'auth',
initialState,
reducers: { /* ... */ },
extraReducers: builder => {
builder.addCase(performLocalLogin.pending, (state, action) => startLoading(state));
builder.addCase(performLocalLogin.rejected, (state, action) => {
//...
});
builder.addCase(performLocalLogin.fulfilled, (state, action) => {
if (action.payload) {
state.rememberMe = action.payload.rememberMe;
state.token = action.payload.token;
}
});
}
})
感谢您的任何帮助!

最佳答案

可以肯定的是,您在那里使用的是标准的内置Dispatch类型,该类型对垃圾邮件一无所知。

根据Redux和RTK文档,您需要定义一个更具体的AppDispatch类型,该类型可以正确了解有关thunk的信息,并在此处声明dispatch就是该类型,例如:

    // store.ts
export type AppDispatch = typeof store.dispatch;

// MyComponent.ts
const dispatch : AppDispatch = useDispatch();

const onSubmit = async () => {
// now dispatch should recognize what the thunk actually returns
}

关于reactjs - 如何使用Redux Toolkit(带有TypeScript)解决 'Property '类型中缺少 'AsyncThunkAction'类型的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62238338/

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