React 中针对不同操作和模式的 Redux 减速器创建方法,以实现干净的代码

问题描述 投票:0回答:1

我的 authSlice 中有这些减速器来跟踪登录和注销。我对此很陌生。制作减速器的方法是什么,例如在登录用户中我们也设置了用户,并且在更新用户中我们也将用户设置得太正确了?所以我们需要有两个reducer来完成同一件事,或者有一个setUser就可以完成这项工作?还有如何处理加载和错误,我想这应该在组件内本地完成。

  const authSlice = createSlice({

  name: "auth",

  initialState,

  reducers: {

    registerUserSuccess: (state, action) => {
      state.user = action.payload;
      state.isAuthenticated = true;
    },

    registerUserFailure: (state) => {
      state.user = null;
      state.isAuthenticated = false;
    },

    loginUserSuccess: (state, action) => {
      state.user = action.payload;
      state.isAuthenticated = true;
    },

    loginUserFailure: (state) => {
      state.user = null;
      state.isAuthenticated = false;
    },

    logoutUser: (state) => {
      state.user = null;
      state.isAuthenticated = false;
    },
  },
});
reactjs react-redux
1个回答
0
投票

您可以创建常见的reducer,例如setUser,

const initialState = {
  user: null,
  isAuthenticated: false,
   isLoading: false,
  error: null,
};

const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    setLoading: (state, action) => {
      state.isLoading = action.payload;
    },
    setError: (state, action) => {
      state.error = action.payload;
    },
    setUser: (state, action) => {
      state.user = action.payload;
      state.isAuthenticated = !!action.payload;
      state.isLoading = false;
      state.error = null;
    },
    clearUser: (state) => {
      state.user = null;
      state.isAuthenticated = false;
      state.isLoading = false;
      state.error = null;
    },
   },
});

在组件中你可以处理错误,

try {
 const user = await loginAPI();
 dispatch(setUser(user));
} catch (error) {
  dispatch(setError(error.message));
} finally {
  dispatch(setLoading(false));
}
© www.soinside.com 2019 - 2024. All rights reserved.