gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:33:01 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com