【问题标题】:Redux with firebase autentication带有 Firebase 身份验证的 Redux
【发布时间】:2022-01-07 22:47:48
【问题描述】:

我正在尝试使用带有 redux 工具包的 redux 为我的反应添加身份验证 这就是我目前拥有的 我创建 createAsyncThunk 的登录功能

 export const signin = createAsyncThunk(
  'authentication/signin',
  async (signinCredentials: userData, { rejectWithValue }) => {
    const { email, password } = signinCredentials;
    await signInWithEmailAndPassword(auth, email, password)
      .then((userCredential) => {
        // Signed in
        const user = userCredential.user;
        return user;
      })
      .catch((error) => {
        console.log(error.message);
        const errorMessage = error.message;
        return rejectWithValue(errorMessage);
      });
  }
);

我有一个 userState 接口,看起来像这样

  export interface userState {
  user: object | null;
  status: 'idle' | 'loading' | 'failed';
  isAuth: boolean;
  message: string;
}

这是初始状态

 const initialState: userState = {
  user: null,
  status: 'idle',
  isAuth: false,
  message: '',
};

我的授权片是这个 问题是当我尝试访问 action.payload 时。我已经用打字稿中的错误标记了这些区域

export const authSlice = createSlice({
  name: 'authentication',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder
      .addCase(signin.pending, (state) => {
        state.status = 'loading';
        state.isAuth = false;
      })
      .addCase(signin.fulfilled, (state, action) => {
        state.status = 'idle';
        state.isAuth = true;
        state.user = action.payload; type void is not assignable to type 'object' | null
      })
      .addCase(signin.rejected, (state, action) => {
        state.status = 'failed';
        state.isAuth = false;
        state.message = action.payload; type 'unknown' is not assignable to type 'string'
      })     
  },
});

我一直试图解决这些问题一段时间,但无法弄清楚发生了什么。我试图留下尽可能多的信息,但如果您需要更多信息。请告诉我。谢谢

【问题讨论】:

    标签: typescript redux redux-toolkit


    【解决方案1】:

    见usage-with-typescript#createasyncthunk

    我们应该为createAsyncThunk 提供正确类型的泛型参数,并为部分或全部这些字段提供类型声明:

    type AsyncThunkConfig = {
      /** return type for `thunkApi.getState` */
      state?: unknown
      /** type for `thunkApi.dispatch` */
      dispatch?: Dispatch
      /** type of the `extra` argument for the thunk middleware, which will be passed in as `thunkApi.extra` */
      extra?: unknown
      /** type to be passed into `rejectWithValue`'s first argument that will end up on `rejectedAction.payload` */
      rejectValue?: unknown
      /** return type of the `serializeError` option callback */
      serializedErrorType?: unknown
      /** type to be returned from the `getPendingMeta` option callback & merged into `pendingAction.meta` */
      pendingMeta?: unknown
      /** type to be passed into the second argument of `fulfillWithValue` to finally be merged into `fulfilledAction.meta` */
      fulfilledMeta?: unknown
      /** type to be passed into the second argument of `rejectWithValue` to finally be merged into `rejectedAction.meta` */
      rejectedMeta?: unknown
    }
    

    这样action.payload 类型 in case reducer 将被正确推断。

    例如

    import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
    
    interface userData {
      email: string;
      password: string;
    }
    
    export const signin = createAsyncThunk<{ email: string }, userData, { rejectValue: string }>(
      'authentication/signin',
      async (signinCredentials: userData, { rejectWithValue }) => {
        const { email, password } = signinCredentials;
        try {
          throw new Error('password incorrect');
        } catch (error) {
          return rejectWithValue(error.message);
        }
      },
    );
    
    export interface userState {
      user: object | null;
      status: 'idle' | 'loading' | 'failed';
      isAuth: boolean;
      message: string;
    }
    const initialState: userState = {
      user: null,
      status: 'idle',
      isAuth: false,
      message: '',
    };
    
    export const authSlice = createSlice({
      name: 'authentication',
      initialState,
      reducers: {},
      extraReducers: (builder) => {
        builder
          .addCase(signin.pending, (state) => {
            state.status = 'loading';
            state.isAuth = false;
          })
          .addCase(signin.fulfilled, (state, action) => {
            state.status = 'idle';
            state.isAuth = true;
            state.user = action.payload;
          })
          .addCase(signin.rejected, (state, action) => {
            state.status = 'failed';
            state.isAuth = false;
            if (action.payload) {
              state.message = action.payload;
            }
          });
      },
    });
    

    【讨论】:

    • 感谢您的帮助,非常感谢
    猜你喜欢
    • 2020-08-02
    • 2019-01-08
    • 2019-02-26
    • 2016-10-05
    • 2021-10-16
    • 2018-01-02
    • 2021-10-30
    • 2019-11-23
    • 1970-01-01
    相关资源
    最近更新 更多