javascript - 在javascript中解构嵌套对象( react )

标签 javascript arrays json reactjs

const [book, ...rest] = this.state.details;
console.log(JSON.stringify(book, null, 2));

日志:

{
  genre: [
    {
      _id: "5ad0ecf98c1cff1e849266f3",
      name: "Fantasy",
      url: "/catalog/genre/5ad0ecf98c1cff1e849266f3",
      id: "5ad0ecf98c1cff1e849266f3"
    }
  ],
  _id: "5ad0ecfc8c1cff1e849266f7",
  title: "The Wise Man's Fear (The Kingkiller Chronicle, #2)",
  summary:
    "Picking up the tale of Kvothe Kingkiller once again, we follow him into exile, into political intrigue, courtship, adventure, love and magic... and further along the path that has turned Kvothe, the mightiest magician of his age, a legend in his own time, into Kote, the unassuming pub landlord.",
  author: {
    _id: "5ad0ecf98c1cff1e849266ee",
    first_name: "Patrick",
    family_name: "Rothfuss",
    date_of_birth: "1973-06-06T00:00:00.000Z",
    name: "Rothfuss, Patrick",
    url: "/catalog/author/5ad0ecf98c1cff1e849266ee",
    id: "5ad0ecf98c1cff1e849266ee"
  },
  isbn: "9788401352836",
  url: "/catalog/book/5ad0ecfc8c1cff1e849266f7",
  id: "5ad0ecfc8c1cff1e849266f7"
};

我要渲染:

render() {
  const [book={}, ...rest] = this.state.details;
  console.log(JSON.stringify(book, null, 2));

// console.log(book.title);

 return (
   <div>
     <h2>{book.title}</h2>
     <p>{book.author.name}</p>
   </div>
 );
}

出现错误:无法读取未定义的属性“title”,如果我将书籍的默认值设置为空对象,我就能获得标题, 但现在我收到错误:无法读取未定义的属性“名称”。 什么是

这是默认状态

state = { details: [], loading: true };  

componentDidMount() {
  fetch(this.props.match.url)
  .then(res => res.json())
  .then(data => this.setState({ details: data, loading: false }))
  .catch(err => console.log(err));
}

最佳答案

我从您的代码和错误中了解到,状态中的 details 对象是异步获取的,因此该组件会在获得所需数据可用之前尝试呈现。

您可以在获取数据时返回 null 或加载消息。

render() {
    const [book={}, ...rest] = this.state.details;
    console.log(JSON.stringify(book, null, 2));

    // console.log(book.title);

    if (!book) return null;

    return (
      <div>
        <h2>{book.title}</h2>
        <p>{book.author.name}</p>
      </div>
    );
}

关于javascript - 在javascript中解构嵌套对象( react ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50137888/

相关文章:

arrays - Go中的初始化结构数组

json - Angular 2 ngClass : Get Got interpolation ({{}}) where expression was expected when trying to display json on html

javascript - jquery 在车速表中移动指针图像

javascript - 崩溃后从 Safari 记录 JavaScript 错误

javascript - 如何在 JavaScript 中找到匹配 bool 条件的数组的第一个元素?

json - fluentd 不解析 JSON 日志文件条目

javascript - 将表达式从模板移动到 Controller

javascript - ASP.NET MVC 中的 Kendo Treemap 工具提示

javascript - 返回我在 HTML 表单中键入的文本

Java-判断数组的位置变化