从子组件接收状态数据时出错

时间:2017-11-15 03:22:51

标签: reactjs

我在处理父组件和子组件之间返回的POST值时遇到错误。我相信这是因为我没有将初始对象设置为空的comments数组,但我不确定如果在undefined属性设置为comments之内,为什么会引发TypeError: Cannot read property 'comments' of undefined at Object.updateCommentsFunc [as updateComments] 状态。

错误消息:

//GET /app and set to state
class PictureFeedContainer extends React.Component{
    constructor(props, context) {
        super(props, context);
        this.state = this.context.data || window.__INITIAL_STATE__ || {pictures: []};
    }

    fetchList() {
        fetch('http://localhost:3000/app')
            .then(res => {
                return res.json();
            })  
            .then(data => {
                console.log(data);
                this.setState({ pictures: data.picture, user: data.user, csrf: data.csrfToken });
            }) 
            .catch(err => {
                console.log(err);
            });
    }

    componentDidMount() {
        this.fetchList();
    }

    render() {
        return (
            <div className="container">
                <h2>Comments List</h2>
                <PictureFeed {...this.state} />
            </div>
        )
    }
};

父组件(获取对象):

class PictureFeed extends React.Component {
    constructor(props){
        super(props);
        this.state = { 
            comments: []
        };
    }

    updateCommentsFunc(newComments){
        console.log("Update Comments Func Triggered");
        //console.log(typeof this.state.comments);
        //console.log(this.state.comments);
        this.setState({comments: [...this.state.comments, newComments]});
    }

    render(){
        return (
            <div>
            { 
                this.props.pictures.map((picture, index) => {
                    return (
                        <div className="row">
                            <div className="col-md-6 col-md-offset-3 picture-card">
                                <PictureCard {...picture} key={picture.pictureIdHash} user={this.props.user} />
                                <Comments {...picture} key={index} pictureId={picture.pictureIdHash} csrf={this.props.csrf} updateComments={this.updateCommentsFunc}/> 
                            </div>
                        </div>
                    );
                })
            }
            </div>
        );
    }
}

父组件(将对象传递给子组件):

export default class Comments extends React.Component {
    render() {
        return (
            <div className="picture-comment-container">
                <CommentForm updateComments={this.props.updateComments} pictureId={this.props.pictureId} csrf={this.props.csrf}/>
                { this.props.picture_comments.map((comment, i) => 
                    <Comment {...comment} key={this.props.pictureCommentId}/>
                )}
            </div>
        );
    }
}

子组件(接收对象):

class CommentForm extends React.Component {
    constructor(props){
        super(props);
        this.state = {
            value: ''
        };

        this.postComment = this.postComment.bind(this);
        this.onChange = this.onChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    postComment(comment, pictureId, csrfToken) {
        console.log(comment);
        console.log(pictureId);
        console.log(csrfToken);
        var body = { comment: comment };
        var route = 'http://localhost:3000/app/picture/' + pictureId + '/comment';
        fetch(route, 
            { 
                method: 'POST', 
                body: JSON.stringify(body), 
                headers: { 
                    'X-CSRF-Token': csrfToken,
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            })
            .then(res => {
                return res.json();
            })  
            .then(data => {
                console.log(data);
                this.props.updateComments(data);
            }) 
            .catch(err => {
                console.log(err);
            });
    }

    onChange(e){
        this.setState({
            value: e.target.value
        });
    }

    handleSubmit(e){
        e.preventDefault();
        this.postComment(this.state.value, this.props.pictureId, this.props.csrf);
    }

    render(){
        return (
            <div className="picture-comment__form">
                <div className="row">
                    <div className="col-md-12">
                        <label>Comment:</label>
                    </div>
                </div>
                <div className="row">
                        <form action={"/app/picture/" + this.props.pictureId + "/comment"} method="post" onSubmit={this.handleSubmit}>
                            <input type="hidden" name="_csrf" value={this.props.csrf}/>
                            <div className="col-md-9">
                                <textarea name="comment" className="picture-comment__form-text-area" onChange={e => this.setState({ value: e.target.value })} value={this.state.value}></textarea>
                            </div>
                            <div className="col-md-3">
                                <button type="submit" className="picture-comment__form-button" disabled={!this.state.value}>Comment</button>
                            </div>
                        </form>
                </div>
            </div>
        )
    }
}

子组件(表单和父函数调用):

th:attr

0 个答案:

没有答案