My error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead

My error: Objects are not valid as a React child (found: object with keys {}). If you meant to render a collection of children, use an array instead

用户注册后,我想在另一个页面上显示他的电子邮件。在 true 的情况下,我有我想要的但在 false 的情况下,它显示错误。我会把那个错误放在下面。请帮我解决这个问题

**My activation page**

import React from "react";
import "./auth.css";

const Activation = (props) => {
  const email = (props.location && props.location.state) || {};

  return (
    <>
      {email ? (
        <div className="activation">
          <i className="vjtal06 fas fa-check-circle"></i>
          <h2>Registration successful.</h2>
          <div className="abn5uhi">
            <p>Thank you. We have send you email to {email}</p>
            <p>
              Pleace click the link in that message to activate your account.
            </p>
          </div>
        </div>
      ) : (
        <div className="activation">
          <i className="vjtal06 fas fa-check-circle"></i>
          <h2>Session Expired</h2>
          <div className="abn5uhi">
            <p>Pleace try again.</p>
          </div>
        </div>
      )}
    </>
  );
};

export default Activation;

Please click here to show my error img

您只需删除此 || {}; 部分 :)

解释: javascript 中有一个叫做 Truthy and Falsy 值的东西,这意味着如果你检查它们可以翻译成 truefalse, 在你的情况下 {} 是 Truthy 值,因此,如果电子邮件为空,它仍然会转换为 true 布尔值

您的电子邮件始终验证为真,因为您的 OR 语句中的空对象既不是虚假的也不是未定义的。

如果你想保留这样的代码,你可以检查对象的长度。

Object.keys(email).length !== 0;