[英]TypeError: Cannot read property '_id' of undefined error
I'm currently developing a blog application.I use react js for frontend and node js for backend.I have this isAuthenticated method.我目前正在开发一个博客应用程序。我将 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;
}};
and I use it here我在这里使用它
<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>
And it's giving me error of TypeError: Cannot read property '_id' of undefined in to={ /user/${isAuthenticated().user._id}
} this part它给了我 TypeError 的错误:Cannot read property '_id' of undefined in to={ /user/${isAuthenticated().user._id}
} 这部分
Please help I'm stocked I can't get the _id from backend I think but I can jwt token whenever I click the application in google chrome dev tools请帮助我有库存
You try to get object with user property from isAuthenticated function but it returns only string or boolean.您尝试使用来自isAuthenticated function 的用户属性获取 object,但它仅返回字符串或 boolean。
Your function can not only return localStorage item but also can return false.您的 function 不仅可以返回 localStorage 项目,还可以返回 false。
So make proper checks like this所以像这样进行适当的检查
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>
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.