React componentDidMount 不更新状态

noa*_*dev 5 javascript ecmascript-6 reactjs

我有一个反应组件,它在构造函数方法中以空白默认状态开始。当 componentDidMount 我想用我通过 AJAX 从我的 API 获得的东西更新状态。

该组件的代码如下所示:

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.componentDidMount = this.componentDidMount.bind(this);

    this.state = {
      ownerInfo:{},
      ownerDogs:[],
      ownerApps:[],
      ownerChat:{},
      posts:[]
    }
  }
  componentDidMount(e){
    var that = this;
    $.get('/api/getUserInit', function(result) {
      console.log(result);
      this.setState({
        ownerInfo: result.ownerInfo,
        ownerDogs: result.ownerDogs,
        ownerNotifications: result.ownerNotifications,
        ownerChat: result.ownerChat,
        posts: result.posts
      });
    }.bind(this));
  }
  addComment(e){
    e.preventDefault();
    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
    };  
    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;
Run Code Online (Sandbox Code Playgroud)

不幸的this.setState({})是,componentDidMount方法中的似乎没有被正确调用,因为没有发生状态更新,我的地图函数期望数组无关并返回错误。

我想在状态更新中使用的对象如下所示:

ownerChat: Object
ownerDogs: Array[1]
ownerInfo: Object
ownerNotifications: Array[0]
posts: Array[2]
Run Code Online (Sandbox Code Playgroud)

除了这种方法,我真的不知道还能尝试什么:/

Vic*_*nch 4

如果我理解正确,您希望在更新状态时重新渲染安装代码。ComponentDidMount 只会在组件初始化时触发。所有更新均通过 ComponentDidUpdate 触发。使用该接口来处理状态更新时将发生的任何事情。

componentDidUpdate: function (prevProps, prevState) {
...
}
Run Code Online (Sandbox Code Playgroud)

更新

抱歉,我是用手机回答这个问题的,我想我没看清楚。如果您想在每次状态发生更改时进行 ajax 调用,那么您将使用 componentDidUpdate,这不是您所要求的。

我注意到您正在构造函数中重新声明 componentDidMount ,它不应该在那里,因为它已经被声明并且您正在覆盖它。除了那段代码之外,我没有看到任何错误。componentDidMount 应该触发并正确更新。但是,我读到当对象为空时,您的地图函数会出错。确保您正在处理空状态,因为您的第一个绑定将为空,然后第二个绑定将有数据。您的映射中的错误可能是这里的罪魁祸首。此示例阻止子级在 ajax 调用返回之前被绑定。

componentDidUpdate: function (prevProps, prevState) {
...
}
Run Code Online (Sandbox Code Playgroud)

让我知道这是否适合您。