javascript - Reactjs + Redux 未处理拒绝(TypeError):无法读取未定义的属性“数据”
问题描述
在使用 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')));
此致
解决方案
您收到错误是因为errors
对象数据中不存在该字段。在这种情况下,它应该做一些条件来检查返回对象的格式,然后再引用它来获取数据。
因此,您可以参考下面的检查程序。
} catch (err) {
if(err.response.data && err.response.data.message){
// todo
}else if(err.response.data && err.response.data.errors){
// todo
}
推荐阅读
- postgresql - 'DISABLE TRIGGER ALL' 是否也会禁用 Postgres 中的域检查?
- javascript - 通过道具将功能从类组件编辑状态传递到基于功能的组件不起作用
- identityserver4 - IdentityServer4 Windows 身份验证缺少回调实现
- java - Kafka Consumer 中更好的错误处理方式
- javascript - 如何在 vue 中全局配置 vee-validate?
- firebase - 如何从 Firebase 存储中获取可公开访问的 URL?
- java - 如何使用 ProcessBuilder 在 Java、MacOS 中运行 ffmpeg 命令
- javascript - Javascript:交互 setTimeout() 和 window.location.assign()
- bash - 如何“包装” bash 命令并解析参数
- python - 对象没有属性“object_list”