user.displayName显示未定义的NextJS

agxfikkp  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(92)
  • 直接进入问题,* 当我执行console.log(user);时,它返回给我一个对象,其中displayName的值是字符串。但是当我执行console.log(user.displayName);时,它应该给我一个值 * Agrim Singh(<--我已经输入了这个值)。

TypeError:无法读取null的属性(读取'displayName')

  • 这里是错误的图像:*

  • 此外,我正在使用Firebase的NextJS。*

  • 以下是文件[postid].jsx的代码:*

const post = ({ post, user }) => {
  const [name, setName] = useState("");
  const [addComment, setAddComment] = useState("");

  const router = useRouter();
  const { postid } = router.query;

  console.log(user); // <--- Working perfectly.
  console.log(user.displayName); // <--- Throwing error.

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!addComment || !name) {
      alert("Please fill all the fields proplerly!");
    } else {
      db.collection("posts").doc(postid).collection("comments").add({
        name: name, // <--- Please ignore this line for now
        comment: addComment,
      });
    }
  };
  return (
    <div className="post container text-center">
      <h2>{post.title}</h2>
      <h5>Created On - {new Date(post.createdAt).toDateString()}</h5>
      <br />
      <img src={post.imageUrl} alt={post.alt} />
      <br />
      <p>{post.description}</p>
      <br />
      <form>
        <div className="form-input">
          <input
            type="text"
            name="name"
            id="name"
            className="name"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Enter Your Name"
          />
        </div>
        <div className="form-input">
          <textarea
            name="add-comment"
            id="add-comment"
            className="add-comment"
            value={addComment}
            onChange={(e) => setAddComment(e.target.value)}
            cols="100"
            rows="3"
            placeholder="Add your Comment"
          ></textarea>
        </div>
        <button onClick={handleSubmit} className="btn-warning">
          Submit
        </button>
      </form>

      <div className="comments">
        <p className="comment">
          <b>
            <i>Name</i>:
          </b>{" "}
          <span>Comment</span> {/* <--- I've not programmed this line because of the error. */}
        </p>
      </div>
    </div>
  );
};

export default post;

export async function getServerSideProps({ params }) {
  const result = await db.collection("posts").doc(params.postid).get();
  return {
    props: {
      post: {
        ...result.data(),
        createdAt: result.data().createdAt.toMillis(),
      },
    },
  };
}

我已经将user属性传递给了文件_app.js中的所有文件。
下面是代码:

export default function App({ Component, pageProps }) {
  const [user, setUser] = useState(null);
  useEffect(() => {
    auth.onAuthStateChanged((user) => {
      if (user) {
        setUser(user);
      } else {
        setUser(null);
      }
    });
  }, []);
  return (
    <div className="app">
      <div className="banner-div">
        <Navbar user={user} />
        <img src="/banner.jpg" alt="School Banner" className="banner" />
      </div>
      <Component {...pageProps} user={user} />
    </div>
  );
}

***编辑:***user.displayName在除[postid].jsx文件外的任何地方都可以工作。
***编辑2:***当我做

console.log(user);

它同时显示null和对象。
图片来源:

np8igboo

np8igboo1#

现在它的工作!

是我干的

const userData = user; // <--- "user" is the prop I called from the file "_app.js"
console.log(userData?.displayName);

在控制台中,它正在显示值。
添加***?***使所有事情工作。
有人能解释一下为什么会这样吗?

相关问题