我仍然相对较新的ReactJS以及使用嵌套数组遍历JSON并将信息显示为道具或状态的最佳实践。在我当前的设置中,我能够访问我的顶级JSON属性,嵌套数组comments
的属性并将它们显示为状态。但是,我想遵循ReactJS的最佳实践,即通过将各个部分分离为props,并访问另一个只有一个值的嵌套数组,将显示此JSON信息的各个元素进行组件化。但是,它似乎没有找到我的comment.app_user[0].fullNameSlug
,错误为TypeError: Cannot read property 'fullNameSlug' of undefined
。
这是由于以下任何原因造成的吗?
key
?JSON:
{
"recIdHash": "Zb2q97rX5n",
"createdAtDateSlug": "9\/1\/2017 7:54 AM",
"recCommentId": 9,
"comment": "Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur porta, eros vitae laoreet pharetra, neque dolor facilisis augue, elementum maximus sapien tortor nec sem. Sed eget est sed felis tincidunt congue. Sed blandit neque vitae tellus interdum, non gravida tortor venenatis.",
"userId": 237,
"created_at": "2017-09-01T11:54:49.089Z",
"updated_at": "2017-09-01T11:54:49.089Z",
"user_id": 237,
"app_user": {
"userIdHash": "M3njEMRjba",
"fullNameSlug": "Steve Matthews",
"userId": 237,
"firstName": "Steve",
"lastName": "Matthews"
}
},
{
"recIdHash": "Zb2q97rX5n",
"createdAtDateSlug": "9\/1\/2017 7:59 AM",
"recCommentId": 10,
"comment": "Sed laoreet felis ac interdum faucibus. Pellentesque non purus commodo, faucibus magna ac, pharetra urna. Sed sapien eros, efficitur in dui venenatis, euismod mattis nisl. Cras a posuere turpis. Morbi suscipit mollis risus, convallis auctor urna. Nam tristique, ex quis sodales tempor, massa urna maximus odio,",
"userId": 240,
"created_at": "2017-09-01T11:59:12.573Z",
"updated_at": "2017-09-01T11:59:12.573Z",
"user_id": 240,
"app_user": {
"userIdHash": "glk4YMY4eG",
"fullNameSlug": "Ruth Wright",
"userId": 240,
"firstName": "Ruth",
"lastName": "Wright"
}
}
}
React Components:
import React from 'react';
import fetch from 'node-fetch';
//Comments - Commentor
class Commentor extends React.Component{
render(props){
return (
<div>
<h4>{props.name}</h4>
</div>
);
}
};
//Comments List
class Comments extends React.Component{
constructor(props, context) {
super(props, context);
this.state = this.context.data || window.__INITIAL_STATE__ || {records: []};
}
fetchList() {
fetch('http://localhost:3000/api/test')
.then(res => {
return res.json();
})
.then(data => {
console.log(data);
let records = data.map((record, index) => {
return(
<div key={index}>
<li>{record.discovery}</li>
<ul>
{
record.record_comments.map((comment, i) => {
return (
<div>
<Commentor name={comment.app_user[0].fullNameSlug} />
<li key={comment.recCommentId}>{comment.comment}</li>
</div>
)
})
}
</ul>
</div>
)
})
this.setState({ records: records });
})
.catch(err => {
console.log(err);
});
}
componentDidMount() {
this.fetchList();
}
render() {
return (
<div>
<h2>Comments List</h2>
<ul>
{this.state.records}
</ul>
</div>
)
}
};
//Comment Container
export default class CommentBox extends React.Component {
render() {
return (
<div className="comment-form">
<h1>Sweet it Worked</h1>
<hr />
<Comments />
</div>
);
}
}