【问题标题】:redux to redux-toolkit refactoringredux 到 redux-toolkit 重构
【发布时间】:2021-04-23 04:35:26
【问题描述】:

当我从服务器收到 401 错误时,有人可以解释为什么这段代码会调度“actions.loginSuccess”吗? 它不应该去'catch' axios 请求的一部分吗?

之前我没有使用 redux 工具包功能

const login = ({username, password}) => async dispatch => {
  await axios.post(`${API_URL}/token/`, {username, password})
    .then(response => {
      dispatch(actions.loginSuccess({ client_id: response?.data.client_id }))
      history.push('/')
    })
    .catch(e => {
      dispatch(actions.loginError({ error: String(e) }))
    })
} 

//actions.js
const login = createAction('@USER/login')
const loginSuccess = createAction('@USER/login-success')
const loginError = createAction('@USER/login-error')

export const actions = {
  login,
  loginSuccess,
  loginError
}

//reducers.js

export const userReducer = createReducer(initialState, builder => {
  builder.addCase(actions.login, draft => {
    draft.loading = true
  })
  
  builder.addCase(actions.loginSuccess, (draft, action) => {
    draft.loading = false
    draft.isLoggedIn = true
    draft.data = { ...draft.data, client_id : action.client_id}
  })
  
  builder.addCase(actions.loginError, (draft, action) => {
    draft.loading = false
    draft.error = action.payload.error
    draft.isLoggedIn = false
    draft.isSignedup = false
  })
}

【问题讨论】:

  • 查看 axios 返回的响应,看看它是返回响应还是抛出错误。您可以在请求中使用 axios validateResponse 设置来控制哪些响应被视为错误。你可能想使用 redux-toolkit 中的createAsyncThunk 函数:redux-toolkit.js.org/api/createAsyncThunk
  • @LindaPaiste 问题是它返回未定义并说无法读取响应的“数据”,因为未定义。

标签: javascript reactjs redux redux-toolkit


【解决方案1】:

有人可以解释为什么这个代码调度'actions.loginSuccess' 当我从服务器收到 401 错误时?是不是应该去“抓住”部分 axios 请求?

 // there's a difference beetween HTTP Status Code and Server Response Body Code.

 // if HTTP status code is not 200, it should dispatched loginError()

 // if HTTP status code is 200, and theres a response body JSON

 // e.g 
 const resp = {
   statusCode: 401,
   message: 'unauthorized',
 }

 // You must make if conditions to handle that error code

这是您的代码的 redux-toolkit 版本,用于处理 HTTP 状态代码 401 或正文响应代码

// import axios & history
import { createSlice } from '@reduxjs/toolkit';

const initialState = {
  data: {},
  loading: false,
  isLoggedIn: false,
  isSignedup: false,
};

// Reducers
const userSlice = createSlice({
  name: '@USER',
  initialState: initialState,
  reducers: {
    loginStart(state) {
      state.loading = true;
    },
    loginSuccess(state, action) {
      state.data = { 
        ...state.data, 
        client_id: action.payload.client_id 
      };
      state.loading = false;
      state.isLoggedIn = true;
    },
    loginError(state, action) {
      state.loading = false;
      state.error = action.payload.error;
      state.isLoggedIn = false;
      state.isSignedup = false;
    },
  },
});

// actions
export const { loginStart, loginSuccess, loginError } = userSlice.actions;
export default userSlice.reducer;

export const login = ({ username, password }) => async (dispatch) => {
  dispatch(loginStart());
  try {
    const response = await axios.post(`${API_URL}/token/`, {
      username,
      password,
    });
    if(response && response.statusCode !== 200){
      return dispatch(loginError({ error: response.message }));
    }

    dispatch(loginSuccess({ client_id: response?.data.client_id }));
    history.push('/');
  } catch (e) {
    dispatch(loginError({ error: String(e) }));
  }
};

不要忘记将userSlice 添加到configureStore()

const reducer = {
  "@USER": userReducers, //got from export default userSlice.reducer
};

export default configureStore({
  reducer,
  middleware,
  devTools: process.env.NODE_ENV !== 'production',
});

【讨论】:

    猜你喜欢
    • 2020-04-24
    • 2021-04-15
    • 2020-12-14
    • 2022-09-25
    • 2021-09-21
    • 2021-12-22
    • 1970-01-01
    • 2021-02-06
    • 2021-08-23
    相关资源
    最近更新 更多