我编写以下代码来从 props 中获取标题。前:
export default function Articleinfo(props) {
const {edge} = props.data.allNodeArticle;
return(
<>
<div>
<h1>Title:{edge[0].title}</h1>
<h2>info:</h2>
</div>
</>
);
};
我收到此错误:无法读取未定义的属性(读取“0”)
但是之后:当我删除花括号时它起作用了
export default function Articleinfo(props) {
const edge = props.data.allNodeArticle;
console.log(edge.nodes[0].title);
const Title = edge.nodes[0].title;
return(
<>
<div>
<h1>Title:{edge.nodes[0].title}</h1>
<h2>info:</h2>
</div>
</>
);
};
有人能解释一下为什么会这样吗?它背后的概念是什么?
花括号用于对象解构
在下面的链接中,解释了对象破坏的语法
所以当你这样做时
const {edge} = props.data.allNodeArticle;
这意味着对象allNodeArticle有一个名为edge的键,您正在访问它
但是,当您执行以下操作并且出现错误时,这意味着 allNodeArticle 不是具有关键边缘的对象,而是它具有数组节点。
const edge = props.data.allNodeArticle;
console.log(edge.nodes[0].title);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句