javascript - 反应:错误:对象作为反应子无效?
问题描述
这个发送 API 调用的钩子工作得很好。在过去的 6 个月里,它一直运行良好。
我不知道为什么它在一条路线上失败了。从 API 返回的所有错误都具有相同的结构:
[{ message: "Invalid username" }, { message: "Invalid password" }]
错误
Error: Objects are not valid as a React child (found: Error: [object Object]).
If you meant to render a collection of children, use an array instead.
钩
export const useRequest = ({ url, method, body, onSuccess }) => {
const [errors, setErrors] = useState(null);
const makeRequest = async (e) => {
try {
setErrors(null);
const { data } = await axios[method](url, { ...body });
if (onSuccess) {
// will invoke callback function that is passed
onSuccess(data);
}
return data;
} catch (err) {
if (err && err.response?.data && err.response?.data.errors) {
// figuring out what is going wrong!
err.response?.data.errors
.map((each) => console.log(typeof each.message)); // returns string
setErrors(
// <== SHOWS ERROR HERE !!!!! WHY??!!
<ul className="errors-list">
{err.response?.data.errors.map((each, index) => (
<li key={index}>{each.message}</li>
))}
</ul>
);
}
}
};
return { makeRequest, errors };
};
这是它第一次显示错误,在过去 6 个月中从未出现过这样的行为。请帮忙!
解决方案
推荐阅读
- python-3.x - 如何使用 python3.x 正确编码 url
- javascript - 选择国家/地区时进行条带连接银行帐户验证
- python - 如何在python中获取季度开始日期
- php - 无法使用 Laravel 5.4 将数据从 $request 存储到 mysql
- vue.js - 仅使嵌套属性具有反应性
- pandas - 在 Pandas 中查找和替换循环
- hadoop - Jenkins 作为 Hadoop EdgeNode 上的 JobServer
- typescript - 如何检查 Typescript 中的哈希映射是否为空
- vb6 - 如何在 Dirlistbox vb6 中显示隐藏文件夹?
- java - 将菜单项的位置更改为左侧