【问题标题】:TypeError: Cannot read property '_id' of undefined errorTypeError:无法读取未定义错误的属性“_id”
【发布时间】:2020-09-03 05:10:27
【问题描述】:

我目前正在开发一个博客应用程序。我使用 react js 作为前端,使用 node js 作为后端。我有这个 isAuthenticated 方法。

export const isAuthenticated = () => {
if (typeof window == 'undefined') {
    return false;
}

if (localStorage.getItem('jwt')) {

    return JSON.parse(localStorage.getItem('jwt'));

}
 else {
    return false;
}};

我在这里使用它

 <li className="nav-item">
                    <Link
                        to={`/user/${isAuthenticated().user._id}`}
                        style={isActive(history, `/user/${isAuthenticated().user._id}`)}
                        className="nav-link"
                    >
                        {`${isAuthenticated().user.name}'s profile`}
                    </Link>
                </li>

它给了我 TypeError 的错误:无法读取未定义的属性 '_id' to={/user/${isAuthenticated().user._id}}这部分

请帮帮我,我想我无法从后端获取 _id,但每当我在 google chrome 开发工具中单击应用程序时,我都可以使用 jwt 令牌

【问题讨论】:

    标签: javascript node.js reactjs web


    【解决方案1】:

    您尝试从 isAuthenticated 函数获取具有 user 属性的对象,但它只返回字符串或布尔值。

    【讨论】:

    • JSON.parse 不返回字符串,除非您的 JSON 只是一个字符串。在这种情况下,它很可能返回一个对象,但 typescript 不知道该对象的结构。
    • 这不是打字稿。这只是 TypeError,因为他试图从原语中获取属性。
    • 啊,对不起,你是对的。我现在太专注于 TS。
    • 我应该输入什么而不是那个
    • 如果 JWT 令牌包含用户对象,您可以对其进行解码。如果没有,您需要进行单独的 API 调用来获取用户对象。 JWT 只是一个框架,不会自动定义您的用户信息。默认情况下,它仅在与 API 对话时用作某种密码替换。
    【解决方案2】:

    您的函数不仅可以返回 localStorage 项目,还可以返回 false。

    所以要像这样进行适当的检查

    isAuthenticated() ? (
      <Link
        to={`/user/${isAuthenticated().user._id}`}
        style={isActive(history, `/user/${isAuthenticated().user._id}`)}
        className="nav-link"
      >
        {`${isAuthenticated().user.name}'s profile`}
      </Link>
    ) : (
      <Link
        to={`/login}`}
        className="nav-link"
      >
        Login
      </Link>
    )
    
    

    【讨论】:

    • 有什么方法可以改变我的 isAuthenticated 因为有几个部分我也使用该方法
    猜你喜欢
    • 1970-01-01
    • 2013-09-03
    • 2022-07-27
    • 2022-09-23
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 2014-12-24
    相关资源
    最近更新 更多