ES6 React componentWillMount不更新状态

时间:2015-11-27 09:51:59

标签: 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);

  this.state = {
      ownerInfo: {},
      ownerDogs: [],
      ownerNotifications: [],
      ownerChat: {},
      posts: []
    };

  }
  componentWillMount(e){
     var that = this;
$.ajax({
  url: '/api/getUserInit',
  method: 'POST',
  data: {},
  success: function(response){
    console.log('Success: ', response);
    that.setState({
      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方法中的ajax请求不会更新当前状态。 (响应obj,是正确的)

我在这里做错了什么? :/

编辑删除了错别字..

2 个答案:

答案 0 :(得分:0)

首先,您在componentWillMount()方法中输错了。 t遗失了。

其次,根据spec,对于ajax请求,您应该使用componentDidMount

编辑:正如大卫所说,你应该使用this.setState()方法改变状态。

答案 1 :(得分:0)

您必须使用that.setState类似

that.state功能
 that.setState({
      ownerInfo: response.ownerInfo,
      ownerDogs: response.ownerDogs,
      ownerNotifications: response.ownerNotifications,
      ownerChat: response.ownerChat,
      posts: response.posts
    });