簡體   English   中英

React componentDidMount不更新狀態

[英]React componentDidMount not updating the state

我有一個react組件,它以構造函數方法中的空白默認狀態開頭。 當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;

不幸的是, componentDidMount方法中的this.setState({})似乎沒有被正確調用,因為沒有狀態更新發生,我期望數組的map函數無關,並返回錯誤。

我想在狀態更新中使用的對象如下所示:

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

我真的不知道在這種方法旁邊還有什么可以嘗試:/

如果我理解正確,您需要在更新狀態時重新呈現安裝代碼。 ComponentDidMount僅在組件初始化時觸發。 所有更新都通過ComponentDidUpdate觸發。 將該接口用於更新狀態時將要發生的任何事情。

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

UPDATE

對不起,我正在用我的手機回答這個問題,我想我沒看對。 如果你想在每次狀態發生變化時進行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;

如果這對您有用,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM