ES6反应js构造函数应该像以前的componentWillMount一样工作,但它没有

时间:2015-11-26 18:43:30

标签: javascript reactjs

我有这个组件应该使用ajax获取一些onLoad状态。 基本语法:

import React from 'react';
import Header from './Header';
import FeedOwnerColumn from './FeedOwnerColumn';
import FeedColumnRight from './FeedColumnRight';
import ReportBug from './ReportBug';

class FeedApp extends React.Component{
  constructor(){
    super();

    this.addComment = this.addComment.bind(this);

    var that = this;
    $.ajax({
      url: '/api/getUserInit',
      method: 'POST',
      data: {},
      success: function(response){
        console.log('Success: ', response);
        that.state = {
          ownerInfo: response.ownerInfo,
          ownerDogs: response.ownerDogs,
          ownerNotifications: response.ownerNotifications,
          ownerChat: response.ownerChat,
          posts: response.posts
        };
      },
      error: function(response){
        console.log('Error: ', response);
      }
    });
  }
  addComment(e){
    e.preventDefault();
    //console.log(e.target.childNodes[0].value);

    var currTime = new Date();
    currTime = currTime.toLocaleString();

    var commentContent = e.target.childNodes[0].value;

    var key = Math.random();
    key = Math.round(key);

    var newComment = {
      id: key,
      name: "Peter Paprika",
      date: currTime,
      thumb_picture:"/imgs/user-q.jpg",
      profile_link: "/user/123",
      content: commentContent,
      like_amount: 0
    };

    //console.log(this.state.posts);

    var postsObj = this.state.posts;

    //console.log(postsObj[0].comments);

    var newComments = postsObj[0].comments;
    newComments.push(newComment);

    console.log(newComments);
    this.setState({posts: postsObj});

  }
  render() {
    return (
        <div className="clearfix wrapper">
          <Header />
          <FeedOwnerColumn />
          <FeedColumnRight posts={this.state.posts} addComment={this.addComment} />
          <ReportBug />
        </div>
    );
  }
}


export default FeedApp;

不幸的是,此方法不提供componentWillMount功能,因为我继续使用"Uncaught TypeError: Cannot read property 'posts' of null"接收的错误确定状态尚未填充,因为地图功能需要帖子状态。

任何想法?

注意

当我使用componentWillMount方法时,我收到以下错误:

Uncaught TypeError: Cannot read property '_currentElement' of null

对象应该是正确的我以前测试过静态状态

0 个答案:

没有答案