My current React sample implementation looks something like:
var MyComponent = React.createClass({
getInitialState: function () {
return {x: []};
},
//..... Some stuff here
render: function () {
var x = this.state.x;
var fx = messages.map(function (m, i) {
return React.createElement(SomeChildComponent, {data: val1});
});
return (
React.createElement('div', {}, fx));
}
});
As you can see, it runs the map
function and iterates over entire array everytime update method is called. Its like doing same thing over and over. Is there a way so that it only adds the ReactChildComponent to just the final array index. Something like:
var MyComponent = React.createClass({
getInitialState: function () {
return {x: []};
},
ComponentWillReceiveProps: function() {
this.state.x.push(this.props.data);
},
render: function () {
var x = this.state.x;
var xl = x. length;
x[xl - 1] = React.createElement(SomeChildComponent, {prop1: val1, prop2: val2});
return (
React.createElement('div', {}, xl));
}
});
So that I can just assign the value to array's final index just once and it just remains there so I don't have to iterate over array everytime. I tried this but somehow the ComponentWillReceiveProps
never gets called and the array ends up being empty (hence selecting length-1 index breaking code).
Is there a neat way to implement this? Is this a good choice? Why do most people just reiterate over entire loop most of the time using map
(as shown in first example).
Assuming my application must give me as much performance as I can achieve as its a real-time app, so I do not want to reiterate over array every time.