簡體   English   中英

Reactjs + Redux 未處理的拒絕(TypeError):無法讀取未定義的屬性“數據”

[英]Reactjs + Redux Unhandled Rejection (TypeError): Cannot read property 'data' of undefined

當使用 react + redux 實現身份驗證時,當我嘗試使用 async / await 在 redux 的操作中注冊用戶時,我在捕獲中收到此錯誤,這是操作的代碼:

import axios from 'axios';
import { setAlert } from './alert';
import { REGISTRO_CORRECTO, REGISTRO_FALLIDO } from './types';

// Registro de Usuario
export const registro = ({
  usuario,
  interfac,
  password,
  descripcion
}) => async dispatch => {
  const config = {
    headers: {
      'Content-Type': 'application/json'
    }
  };

  const body = JSON.stringify({ usuario, password, interfac, descripcion });

  try {
    // Conex to backend
    const res = await axios.post('http://localhost:5000/api/usuarios', body, config);

    dispatch({
      type: REGISTRO_CORRECTO,
      payload: res.data
    });
  } catch (err) {
    const errors = err.response.data.errors;

    if (errors) {
      errors.forEach(error => dispatch(setAlert(error.msg, 'danger')));
    }

    dispatch({
      type: REGISTRO_FALLIDO
    });
  }
};

運行提交給了我這個錯誤:

  26 |      payload: res.data
  27 |    });
  28 |  } catch (err) {
> 29 |    const errors = err.response.data.errors;
     | ^  30 | 
  31 |    if (errors) {
  32 |      errors.forEach(error => dispatch(setAlert(error.msg, 'danger')));

此致

您收到錯誤是因為對象數據中不存在字段errors 在這種情況下,它應該在引用從中獲取數據之前檢查返回對象的格式。

所以,你可以參考下面的檢查你的程序。

  } catch (err) {
    if(err.response.data && err.response.data.message){
       // todo
    }else if(err.response.data && err.response.data.errors){
       // todo
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM