React componentDidMount未更新状态

React componentDidMount not updating the state

本文关键字:状态 更新 componentDidMount React      更新时间:2023-09-26

我有一个react组件,它在构造函数方法中以空白默认状态开始。当组件DidMount时,我想用我通过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;

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

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

ownerChat: Object
ownerDogs: Array[1]
ownerInfo: Object
ownerNotifications: Array[0]
posts: Array[2]

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

如果我理解正确,您希望在更新状态时重新发送安装代码。ComponentDidMount将仅在组件初始化时激发。所有更新都是通过ComponentDidUpdate触发的。将该接口用于更新状态时将要发生的任何事情。

componentDidUpdate: function (prevProps, prevState) {
...
}

更新

对不起,我在用手机回答这个问题,我想我没有读对。如果您想在每次状态发生更改时进行ajax调用,则可以使用componentDidUpdate,而这不是您所要求的。

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

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();
    // only adding functions not defined by super
    this.addComment = this.addComment.bind(this);
    this.state = {
      hasData: false,
      ownerInfo:{},
      ownerDogs:[],
      ownerApps:[],
      ownerChat:{},
      posts:[]
    }
  }
  componentDidMount(e){
    var that = this;
    $.get('/api/getUserInit', function(result) {
      console.log(result);
      console.log('isMounted: ' + this.isMounted());
      if (this.isMounted()) {
        this.setState({
            hasData: true,
            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() {
    var content = '';
    if (this.state.hasData) {
        content = ( 
          <div>
             <Header />
             <FeedOwnerColumn />
             <FeedColumnRight posts={this.state.posts} addComment={this.addComment} />
             <ReportBug />
          </div>
         );
    }
    return (
        <div className="clearfix wrapper">
            {{ content }}
        </div>
    );
  }
}

export default FeedApp;

让我知道这是否适合你。