首页 > 解决方案 > 反应:错误:对象作为反应子无效?

问题描述

这个发送 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 个月中从未出现过这样的行为。请帮忙!

标签: javascriptnode.jsreactjsreact-nativereact-redux

解决方案


推荐阅读