【发布时间】:2020-09-26 00:25:32
【问题描述】:
我正在使用 Redux Toolkit 和下面的 thunk/slice。我认为我可以通过等待 thunk 承诺解决 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时出现错误:
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;
}
});
}
})
感谢您的帮助!
【问题讨论】:
标签: reactjs typescript redux redux-thunk redux-toolkit