首页 > 解决方案 > 为什么我的 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>

我收到此错误:

TypeError:无法读取未定义的属性“用户名”

你以前有没有遇到过这个奇怪的问题?

为了进一步研究,这里是完整的数据对象。这来自从同一应用程序中的相邻文件导出的模拟数据对象。没有对后端或任何东西的网络请求,所以这里不应该有任何异步的东西(我可能错了):

{
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>&ldquo;{content}&rdquo;</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

标签: javascriptjsonreactjsdestructuring

解决方案


推荐阅读