React 和 Redux 工具包 - 承诺后拒绝

Jer*_*olo 3 reactjs react-native redux redux-thunk react-redux

我正在开发一个 React Native 应用程序。我有一个注册屏幕,其中有一个按钮,onclick:

const handleClick = (country: string, number: string): void => {
    dispatch(registerUser({ country, number }))
      .then(function (response) {
        console.log("here", response);
        navigation.navigate(AuthRoutes.Confirm);
      })
      .catch(function (e) {
        console.log('rejected', e);
      });
  };
Run Code Online (Sandbox Code Playgroud)

注册用户函数:

export const registerUser = createAsyncThunk(
    'user/register',
    async ({ country, number }: loginDataType, { rejectWithValue }) => {
        try {
            const response = await bdzApi.post('/register', { country, number });
            return response.data;
        } catch (err) {
            console.log(err);
            return rejectWithValue(err.message);
        }
    },
);
Run Code Online (Sandbox Code Playgroud)

我有一个extraReducers确实被称为的东西,证明它被有效地拒绝了。

.addCase(registerUser.rejected, (state, {meta,payload,error }) => {
    state.loginState = 'denied';
    console.log(`nope : ${JSON.stringify(payload)}`);
})
Run Code Online (Sandbox Code Playgroud)

但注册组件会正常处理,记录“此处”并导航到“确认”屏幕。这是为什么?

HMR*_*HMR 12

用 创建的 thunkcreateAsyncThunk总是会解析,但如果你想在调度 thunk 的函数中捕获它,你必须使用unwrapResults

createAsyncThunk 生成的 thunk 将始终返回一个已解决的 Promise,其中包含已完成的操作对象或已拒绝的操作对象(视情况而定)。

调用逻辑可能希望将这些操作视为原始承诺内容。Redux Toolkit 导出一个 unwrapResult 函数,该函数可用于提取已完成操作的有效负载,或抛出错误,或者抛出由拒绝操作中的rejectWithValue创建的有效负载(如果可用):

import { unwrapResult } from '@reduxjs/toolkit'

// in the component
const onClick = () => {
  dispatch(fetchUserById(userId))
    .then(unwrapResult)
    .then(originalPromiseResult => {})
    .catch(rejectedValueOrSerializedError => {})
}
Run Code Online (Sandbox Code Playgroud)