ItGo.me Focus on IT Recommend

Home > javascript - React State Change Not Causing component to Re-Render

javascript - React State Change Not Causing component to Re-Render

2020腾讯云双十一活动,全年最低!!!(领取3500元代金券),
地址https://cloud.tencent.com/act/cps/redirect?redirect=1074

【阿里云】双十一活动,全年抄底价,限时3天!(老用户也有),
入口地址https://www.aliyun.com/1111/home

I'm still new to ReactJS, and I've run into a bit of a snag. I'm trying to implement pagination in a React component; however, even though my pagination function is being called successfully the state change is not causing the component to Render again.

I'm using one function to get the initial data (getMainFeed) and then a second one (getMoreItems) for the pagination. The second function is called by my 'handleScroll' function. Interestingly enough, when I replace the 'getMoreItems' function with the 'getMainFeed' function, the state change causes the component to render the additional data perfectly. Unfortunately I need to hit these two separate APIs and I don't think it would be in good form to combine the two calls into one function. So is there a way that I can get 'getMoreItems' to render the new items to the screen?

var data = [];


var GridView = React.createClass({
  getInitialState: function() {
    window.addEventListener("scroll", this.handleScroll);
    return {
      data: [],
      page: 0,      //for pagination
      loadingFlag: false,
    };
    },

  getMainFeed: function() {

    var nextPage = 1; //increase the page count
    ajax_url = "http://127.0.0.1:8200/api/content/main/";
    ajax_type = "GET";
    ajax_data = {
       'BatchCount': "20"
    };

    $.ajax({
       url: ajax_url,
       type: ajax_type,
       contentType: 'application/x-www-form-urlencoded',
       data: ajax_data,

       dataType: 'json',

    success: function(data) {
      this.setState({
        data: data,
        loadingFlag:false,
        page: 2

      });
      //loading("off");
    }.bind(this),
    error: function(xhr, status, err) {
      console.error(this.props.url, status, err.toString());
    }.bind(this)

    });

   }, //end function
   getMoreItems: function() {
    var nextPage = this.state.page+1; //increase the page count
    ajax_url = "http://127.0.0.1:8200/api/content/page/1/";
    ajax_type = "GET";
    ajax_data = {
       'BatchCount': "20"
    };

    $.ajax({
       url: ajax_url,
       type: ajax_type,
       contentType: 'application/x-www-form-urlencoded',
       data: ajax_data,

       dataType: 'json',

    success: function(data) {
      this.setState({
        data: data,
        loadingFlag:false,
          page: nextPage
      });

    }.bind(this),
    error: function(xhr, status, err) {
      console.error(this.props.url, status, err.toString());
    }.bind(this)
    });

 }, //end function
  componentDidMount: function() {
    //loading("on");
    this.getMainFeed();
  },
  handleScroll:function(e){
    //this function will be triggered if user scrolls
    var windowHeight = $(window).height();
    var inHeight = window.innerHeight;
    var scrollT = $(window).scrollTop();
    var totalScrolled = scrollT+inHeight;
    if(totalScrolled+1200>windowHeight){  //user reached at bottom
      if(!this.state.loadingFlag){  //to avoid multiple request 
          this.setState({
            loadingFlag:true,  
          });
          //loading("on");
          this.getMoreItems();
      }
    }
  },
  componentDidUpdate: function() {

    $('#grid-container').imagesLoaded( function() {
      MasonryInit();
    }); 
  },
  render: function() {
      return (
        <div id="feed-container-inner">
          <GridMain data={this.state.data} />
        </div>

      );
    }
  });
javascript pagination reactjs infinite-scroll
|
  this question
asked Aug 11 '15 at 3:42 Bill Walters 55 1 8      is success being executed in getMoreItems? –  knowbody Aug 11 '15 at 6:49      Yep, success always is called. I wasn't setting the data properly. –  Bill Walters Aug 11 '15 at 19:37

 | 

2 Answers
2

When the state change it will re-render. Also you saw that it was working with your getmainfeed function.

So I think that your getmoreitems function just do not success. Have you verified that this call succeed ?


|
  this answer
answered Aug 11 '15 at 4:31 François Richard 2,517 4 15 34      Nope, the function always succeeded. Turns out I had to concatenate the data –  Bill Walters Aug 11 '15 at 19:35

 | 

The problems turns out to be that I wasn't concatenating the data to the end of the existing data like so data: this.state.data.concat(data),.

Recommend:javascript - React component not updating on state change

n when the data comes back, I want it to populate the options of the select. I am setting the state of tagList when the data comes back and passing this.state.tagList as a prop to the component. But when I update state, it's not updating th

This surprises me, because I would have expected the getMoreItems function to simply replace the existing data.


|
  this answer
answered Aug 11 '15 at 19:35 Bill Walters 55 1 8      It doesn't make sense. I think that the render function was triggered and your view rerender, however the format was bad and your view cound'lt display it. even if rerendered. –  François Richard Aug 11 '15 at 22:06      Ah that makes sense, thanks for the help François. –  Bill Walters Aug 11 '15 at 22:07      Also you shouldn't change state via 'this.state'. You should always change via setState. From react.js implementation of setState: Sets a subset of the state. Always use this to mutate state. You should treat this.state as immutable. –  Abhinav Singi Sep 2 '15 at 15:12      JavaScripts Array.concat returns a new array without modifying the existing one, so use like this is fine. See MDN docs –  Alex Young Nov 22 '16 at 17:27

 | 

Recommend:javascript - Re-render child component in React or change child state

constructor(props) { super(props); this.state = {show: props.show || false}; this.close = this.close.bind(this); this.open = this.open.bind(this); } close() { this.setState({show: false}

------splitte line----------------------------