因此,我尝试从 json 文件在 React 中动态创建内容页面,该文件工作正常,直到到达嵌套对象。
这是存储在 JSON 文件中的 JSON 对象之一的片段。链接对象是我访问时遇到问题的对象。我能够完美地检索其他属性。
{
"core-topics": [
{
"id": "coding",
"name": "Coding",
"headerColour": "blue",
"description": "Learn how to build your very own website!",
"image": "https://www.bitdegree.org/tutorials/wp-content/uploads/2018/08/what-is-a-web-developer.jpg",
"link": [
{
"id": "coding-item-one",
"name": "Java"
},
{
"id": "coding-item-two",
"name": "C++"
},
{
"id": "coding-item-three",
"name": "Python"
}
]
},
我有一个模板组件,它将所有内容呈现为 HTML。这只是一个简单的模板组件。我已尝试对链接属性进行 .map ,但由于尚未声明任何内容,因此我只得到“未定义或空属性”。从逻辑上讲,我想在“编写器组件”中执行此操作,但不知道如何操作。
render(){
return(
<Container>
<HeaderImage headerImage = {this.props.image}>
<ImageTextContainer>
<H1> {this.props.name} </H1>
<Stripe stripeColour = {this.props.headerColour}/>
<P> {this.props.description} </P>
{/* This is the nested object (I want to access the ID and name properties) */}
<p> {this.props.link}</p>
</ImageTextContainer>
</HeaderImage>
</Container>
)
}
这就是我通过每个对象唯一 ID 动态映射所有数据的方式。理想情况下,我想要一种映射链接对象的方法,但在使用这种方法时无法弄清楚如何进行。
const Writer = ({match: {url}, coreTopics}) => {
return (
<div>
// This returns a page for each of the objects in my JSON file along with all the properties passed in from the template component
<Route path = {`${url}/:topicId`} render = {
({ match }) =>
<TopicHeaderCard {...coreTopics.find(topic => topic.id === match.params.topicId)}/>}
/>
</div>
)
}
那么有没有办法可以使用此方法访问链接对象属性?或者是否有另一种技术更适合这种方法?
非常感谢所有帮助!
最佳答案
渲染前可以检查链接,只需添加验证!!this.props.link
render(){
return(
<Container>
<HeaderImage headerImage = {this.props.image}>
<ImageTextContainer>
<H1> {this.props.name} </H1>
<Stripe stripeColour = {this.props.headerColour}/>
<P> {this.props.description} </P>
{/* This is the nested object (I want to access the ID and name properties) */}
{!!this.props.link && this.props.link.map((link)=>{
<div key={link.id}>
<p>link.id</p>
<p>link.name</p>
</div>
})}
</ImageTextContainer>
</HeaderImage>
</Container>
)
}
关于javascript - 如何使用可展开的 props 来检索 ReactJS 中的嵌套对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61171321/