【发布时间】:2017-11-16 13:06:21
【问题描述】:
我有一些获取的数据返回一个对象数组,每个对象都有一个嵌套的对象数组。我提到的嵌套数组blog_comments 可以从我的页面上的表单中动态插入一个值,并且我有一个处理 POST 和数组插入的父子函数,但我似乎无法找到一种方法将数组最初设置为每个 blog_comments 对象。有没有办法做一个嵌套映射并使用setState 设置对象?这应该在我的有状态组件的构造函数中处理吗? componentDidMount?
JSON:
[
{
"blogId": 105,
"blogDateSlug": "08\/15\/2017",
"title": "Working Hard",
"discovery": "lorem ipsum",
"created_at": "2017-08-15T23:23:50.329Z",
"updated_at": "2017-08-15T23:25:23.826Z",
"blog_user": {
"fullNameSlug": "Mike Rellis",
"firstName": "Mike",
"lastName": "Rellis",
"picture": "https://s3.amazonaws.com/certain-web-assets/user-example-two.jpg"
},
"blog_comments": [
{
"createdAtDateSlug": "8\/15\/2017 11:10 AM",
"comment": "Great work with this article",
"created_at": "2017-08-16T10:44:52.492Z",
"updated_at": "2017-08-16T10:44:52.492Z",
"blog_user": {
"fullNameSlug": "Sandra Matthews",
"firstName": "Sandra",
"lastName": "Matthews",
"picture": "https://s3.amazonaws.com/certain-web-assets/user-example-one.jpg"
}
}
]
}
]
这是我获取的数据:
class BlogFeedContainer extends React.Component{
constructor(props, context) {
super(props, context);
this.state = this.context.data || window.__INITIAL_STATE__ || {blogs: []};
}
fetchList() {
fetch('http://localhost:3000/api/test')
.then(res => {
return res.json();
})
.then(data => {
console.log(data);
this.setState({ blogs: data.blog, user: data.user, csrf: data.csrfToken });
})
.catch(err => {
console.log(err);
});
}
componentDidMount() {
this.fetchList();
}
render() {
return (
<div className="container">
<BlogFeed {...this.state} />
</div>
)
}
};
这里是循环骨架,它将返回我尝试设置到我的 comments 状态数组的正确对象:
this.props.blogs.map((blog, index) => {
{ this.props.blog_comments.map((comment, i) => {
})
})
这是处理数组插入的组件,应该处理初始数组状态:
class BlogFeed extends React.Component {
constructor(props){
super(props);
this.state = {
comments: []
};
this.updateCommentsFunc = this.updateCommentsFunc.bind(this);
}
componentDidMount(){
this.props.blogs.map((blog) => {
console.log("setCommentArr() triggered");
console.log(blog);
})
}
setCommentArr(){
}
updateCommentsFunc(newComments){
console.log("Update Comments Func Triggered");
var updatedCommentArr = this.state.comments.slice();
updatedCommentArr.push(newComments)
this.setState({comments: updatedCommentArr});
console.log(this.state.comments);
}
render(){
return (
<div>
{
this.props.blogs.map((blog, index) => {
return (
<div className="row">
<div className="col-md-6 col-md-offset-3 blog-card">
<BlogCard {...blog} key={blog.blogIdHash} user={this.props.user} />
<Comments {...blog} key={index} blogId={blog.blogIdHash} csrf={this.props.csrf} updateComments={this.updateCommentsFunc}/>
</div>
</div>
);
})
}
</div>
);
}
}
【问题讨论】:
标签: reactjs