【问题标题】:Field value showing null value显示空值的字段值
【发布时间】:2020-08-04 13:05:38
【问题描述】:
const book1 = this.state.books[0]; //giving one book
console.log(book1); //output->{id: 1, bookname: "Physics", price: 600, author: "ABC", pages: 567, …}
const {id,bookname,price,author,pages,category} = {book1};
console.log(price); //output->undefined

我已经尝试了很多东西。如何获得特定财产的价值? 这是 JSON 文件:

 [
    {
            "id": 1,
            "bookname": "Physics",
            "price": 600,
            "author": "ABC",
            "pages": 567,
            "category" : "Science"
    }

]

【问题讨论】:

标签: json reactjs output undefined state


【解决方案1】:

是的,正如 Jake 所提到的,您在此处尝试执行的操作称为解构赋值。所以按照正确的语法,

const { id, bookname, price, author, pages, category } = book1;

这实际上意味着,

const id=book1.id
const bookname=book1.bookname

等等。您可以查看https://javascript.info/destructuring-assignment,了解有关解构赋值的更多信息。

【讨论】:

  • TypeError:无法解构“book1”的属性“id”,因为它未定义。 39 | > 41 |常量 {id,书名,价格,作者,页面,类别} = book1; | ^ 42 | console.log(bookname);
【解决方案2】:

显示的 JavaScript 对象解构无效,因为 book1 周围有花括号。

去掉那些大括号:

const { id, bookname, price, author, pages, category } = book1;

这是一个更简单的例子:

> const book = { price: 600 }
undefined
> const { price } = book
undefined
> price
600

【讨论】:

  • TypeError:无法解构“book1”的属性“id”,因为它未定义。 39 | > 41 |常量 {id,书名,价格,作者,页面,类别} = book1; | ^ 42 | console.log(bookname);
  • id of book1 未定义。这可能是由许多原因造成的:在加载数据之前进行解构、错字、其中一本书没有 id 等等。这是你的下一个挑战@NancyGupta!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-02
  • 1970-01-01
相关资源
最近更新 更多