javascript - Fill a container with content using React.JS -
i have container element, react component, specific height. have api returns blocks of contents of variable length, based on requested id.
<contents/>
i want request new block of content api until container overflowing.
my code works, rerenders content blocks , adds 1 in each render, until container full. seems bad approach.
class contents extends react.component { constructor() { super(); this.state = { numelements: 0 }; } render() { const elements = []; for(let = 0; < this.state.numelements; i++) { elements.push(this._getelementcontents(i)); } return(<div id="contents"> {elements.map(element => element)} </div>); } componentdidmount() { // start 'filling loop' this._addelement(); } componentdidupdate() { // keep adding stuff until container full if(document.getelementbyid('contents').clientheight < window.outerheight - 400) { this._addelement(); } } _addelement() { // setstate cause render() called again this.setstate({numelements: this.state.numelements + 1}); } _getelementcontents(i) { // simplified, gets stuff api: let contents = api_response; return(<element key={i} body={contents} />); } }
how can append elements container until filled, without re-adding, re-querying api , re-rendering existing elements on each loop?
i can't see how calling api or under condition. understanding should 2 things.
keep elements
array state
object , push new elements whenever arrive.
use shouldcomponentupdate
instead of componentdidupdate
same condition judge when have request more elements api.
eventually draw state.elements
. whenever receive new 1 use local elements got redraw component instead of making api calls on again
Comments
Post a Comment