javascript - 为什么我的 JavaScript 对象属性实际上是已定义的却无法访问?
问题描述
这是对象。它是数据树中的二级对象:
user: {
userId: 3,
username: 'aragorn',
},
我的 React 组件正在解构其父对象并使其可用于整个组件。当我使用此代码呈现完整的用户对象时:
<p className="small">
{`Submitted by ${JSON.stringify(user)}`}
</p>
我得到一个包含所有用户属性的完整字符串化对象:
当我尝试仅从“用户”对象访问“用户名”属性时:
<p className="small">
{`Submitted by ${JSON.stringify(user.username)}`}
</p>
我收到此错误:
你以前有没有遇到过这个奇怪的问题?
为了进一步研究,这里是完整的数据对象。这来自从同一应用程序中的相邻文件导出的模拟数据对象。没有对后端或任何东西的网络请求,所以这里不应该有任何异步的东西(我可能错了):
{
title: "The Hefalump's Tale",
page: '32',
line: '1',
author: 'Joni E. Driskill',
genre: 'Sci-fi',
type: 'Motivational',
content: 'The grass is greener on the other side, unless, in actuality and reality, it is not. I guess in that case, you can just give up on anything nice in life.',
claps: 23,
id: 4,
user: {
userId: 3,
username: 'aragorn',
},
comments: [
{
commentId: 0,
quoteId: 0,
content: 'Comment content',
userId: 'userId',
claps: 2,
date: 2,
},
{
commentId: 1,
quoteId: 1,
content: 'Comment content',
userId: 'userId',
claps: 4,
date: 1,
},
{
commentId: 2,
quoteId: 2,
content: 'Comment content',
userId: 'userId',
claps: 12,
date: 0,
},
],
},
这里是我的 React 组件,称为 'Meta',将 'quote' 对象作为道具引入。有问题的主要线是底部,但如果你愿意,也可以随意查看我的道具解构:
import React from 'react';
import Clap from '../mechanics/Clap';
import Report from '../mechanics/Report';
const Meta = ({
quote: {
content,
title,
author,
page,
line,
genre,
type,
claps,
id,
user,
},
}) => (
<div className="discussion-meta mb2">
<h1>“{content}”</h1>
<hr />
<div className="columns is-spaced-around pb3 text-align-left">
<div className="column">
<h3>{title}</h3>
<p>
<small>by {author}</small>
</p>
{page ?
<p>
<small>page {page}{line ? `, line ${line}` : ''}</small>
</p>
: null
}
</div>
<div className="column text-align-right">
<p>
<span className="tag-purple small">{genre}</span>
</p>
<p>
<span className="tag-green small">{type}</span>
</p>
</div>
</div>
<div className="columns">
<div className="column">
<p className="small">
{`Submitted by ${JSON.stringify(user.username)}`}
</p>
</div>
</div>
<div className="columns">
<div className="column">
<Clap claps={claps} />
</div>
<div className="column">
<Report id={id} />
</div>
</div>
</div>
);
export default Meta;
我在 CodeSandbox 中重新创建了,它可以工作!哇! https://codesandbox.io/s/4q9nlywl1x
解决方案
推荐阅读
- excel - 使用 VBA 和 Selenium WebDriver 登录网站
- python - 我的一个循环不起作用,有人可以给我一个原因吗?
- java - 输出问题,if语句在不应该执行的时候被执行
- reactjs - 如何在反应样式的组件中使用材质颜色?
- javascript - React 图像在本地加载,但不在 AWS Amplify 上
- java - 我如何在 jeroo 做一个盒子实验室?
- excel - 将缩放视图自动调整到表格中的活动/可见单元格?
- c++ - 如何将程序输出重定向为其输入
- sql-server - Invoke-ASCmd 不是 Powershell 模块 sqlserver(版本 21.1.18228)中的 cmdlet
- javascript - Javascript:在代码中使用字符串作为变量名