实际上,为什么定义了我的JavaScript对象属性?

时间:2019-02-14 22:24:05

标签: javascript json reactjs destructuring

这里是对象。它是数据树中的第二级对象:

user: {
  userId: 3,
  username: 'aragorn',
},

我的React组件正在分解其父对象,并使其可用于整个组件。当我使用以下代码呈现完整用户对象时:

<p className="small">
  {`Submitted by ${JSON.stringify(user)}`}
</p>

我得到一个具有所有用户的属性的完整字符串对象:

Complete object renders in string form

当我尝试仅从“用户”对象访问“用户名”属性时:

<p className="small">
  {`Submitted by ${JSON.stringify(user.username)}`}
</p>

我收到此错误:

TypeError: Cannot read property 'username' of undefined

您以前遇到过这个奇怪的问题吗?

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

{
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,
  },
],

},

HERE是我的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中重新创建,并且可以使用! WTF! https://codesandbox.io/s/4q9nlywl1x

0 个答案:

没有答案