Reactjs + Redux未处理的拒绝(TypeError):无法读取未定义的属性“ data”

时间:2020-02-17 16:29:23

标签: javascript reactjs redux async-await react-redux

当使用react + redux实现身份验证时,当我尝试使用async / await在redux的操作中注册用户时,我在catch中收到此错误,这是操作的代码:

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')));

最诚挚的问候

1 个答案:

答案 0 :(得分:0)

您收到错误消息,因为对象数据中不存在字段errors。在这种情况下,应先确定返回对象的格式,然后再引用该对象以获取数据。

因此,您可以参考下面的检查程序。

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