【问题标题】:Possible to Set Initial Array to Returned Nested Objects可以将初始数组设置为返回的嵌套对象
【发布时间】: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


    【解决方案1】:

    使用componentWillReceiveProps(nextProps) 生命周期方法。在这里,您可以在您的BlogFeed 组件上调用this.setState(),以响应提取完成后props 的更改。

    您将传递给this.setState() 的内容取决于您希望comments 在组件状态中的表示方式以及您要对该状态执行的操作。

    可能是扁平化的 cmets 数组:

    const comments = nextProps.blogs
      .reduce((arr, blog) => arr.concat(blog.blog_comments), []);
    

    或者它可能是一个被键入blogId的cmets对象:

    const comments = nextProps.blogs
      .reduce((obj, blog) => Object.assign(obj, { [blog.blogId]: blog.blog_comments }), {});
    

    然后只需调用所需的状态更改:

    this.setState({ comments })
    

    【讨论】:

    • 感谢您的回答!什么会传递给this.setState(),我能否在这个生命周期方法中添加我的问题中提到的.map 功能?我以前从未使用过这种方法,很想看看映射和设置是如何发生的。
    • 编辑了答案以显示如何在 componentWillReceiveProps() 生命周期方法期间设置状态。最终,这取决于您的用例,但我会构建状态更改对象,然后以该对象作为参数调用 setState()。
    猜你喜欢
    • 1970-01-01
    • 2013-11-08
    • 2015-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    相关资源
    最近更新 更多