简体   繁体   English

在功能组件中,useContext 在 console.log 中工作,但在渲染时返回错误

[英]In functional component useContext works in console.log but returns error on render

I have been looking around, but can't find a definite answer.我一直在四处寻找,但找不到明确的答案。 I have wrapped my app in <AuthContext> , I have passed props and tried return <div>{props.user.username}</div> but nothing works, just getting the same TypeError: Cannot read property 'username' of undefined over and over again.我已经将我的应用程序包装在<AuthContext>中,我已经传递了道具并尝试return <div>{props.user.username}</div>但没有任何效果,只是得到相同的TypeError: Cannot read property 'username' of undefined over一遍又一遍。 Am I doing something fundamentally wrong here or is there a simple answer to this?我在这里做一些根本错误的事情还是有一个简单的答案?

import React, { useContext } from "react";
import { AuthContext } from "../../context/auth";

const HeaderBar = (props) => {
    const {user: { user }} = useContext(AuthContext);

    if (user) {
        console.log(user.username); // Returns user in console log, so everything seems to be working fine
      }

    return <div>{user.username}</div> // Throws an error "TypeError: Cannot read property 'username' of undefined"
}

export default HeaderBar

That seems pretty weird.这似乎很奇怪。 However, I may have an explanation (but I'm not sure this will solve your problem).但是,我可能有一个解释(但我不确定这会解决你的问题)。

You probably have something in your app that is changing, and make that component rerender.您的应用程序中可能有一些东西正在发生变化,并使该组件重新呈现。 This means that you could have multiple logs in the console.这意味着您可以在控制台中有多个日志。 The user can be defined when the component is rendered for the first time, and immediately change (for external reason?), and changing the user variable to undefined.可以在第一次渲染组件时定义user ,并立即更改(出于外部原因?),并将user变量更改为未定义。

Here are some tips you can use for debugging:以下是一些可用于调试的提示:

console.log(user.username) 
// throw an error if user is not defined, execution is stopped

console.log(user?.username) 
// returns undefined if user is not defined

console.log(user?.username ?? "username not defined") 
// return "username not defined" only if user is undefined or username is (undefined or null)

Using the 2nd or the 3rd syntaxe may help you avoid the error.使用第 2 或第 3 语法可以帮助您避免错误。 You can try:你可以试试:

const HeaderBar = (props) => {
    const {user: { user }} = useContext(AuthContext);

    if (user) {
        console.log(user?.username ?? "username not defined");
      }

    return <div>{user?.username ?? "username not defined"}</div> // Cannot throw an error
}

This answer will not fix your problem but I hope it can help you;此答案不会解决您的问题,但希望对您有所帮助; ;) ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM