Reputation: 406
I'm new to ReactJS and started developing an application in it.
The application has an array of 100 Image URLS and I'm showing those images in webpage and each image has a remove button on top of it which on click remove the Image URL from the Array.
I'm able to develop the application.
My problem is whenever I remove an image, Application is making network calls again to get the images of others. For example if I removed 5th Image there are network calls to get images of 6 to 100. Is there any way I can stop making these network calls as Images are already loaded.
I developed the same application in AngularJS and it is working very well and when I remove an image there are no network calls to get the other images.
var Image= React.createClass({
removeImage: function(){
this.props.removeImage(this.props.index);
},
render: function(){
var divStyle = {
backgroundImage: 'url(' + this.props.imageUrl + ')'
};
return(
<div className="imageWrapper">
<div>Image {this.props.index+1}</div>
<div className="image" style={divStyle}>
<button className="removeButton" onClick={this.removeImage} >Remove</button>
</div>
</div>
)
}
})
var Images= React.createClass({
getInitialState: function() {
console.log('Images: getInitialState');
return {data: imageUrls};
},
removeImage: function(index){
console.log('Images: removeImage: index: ',index);
this.state.data.splice(index,1);
this.setState({data: this.state.data});
console.log('end if removeImage method');
},
render: function(){
console.log('in Images: render method: this :', this);
var imagesNodes = this.state.data.map(function(imageUrl, index){
return (
<Image key={index} imageUrl={imageUrl} index={index} removeImage={this.removeImage}/>
)
},this);
return(
<div className="images">
{imagesNodes}
</div>
)
}
});
ReactDOM.render(
<Images />,
document.getElementById('imagesContainer')
)
Upvotes: 1
Views: 54
Reputation: 46553
Your key is based on the index in your array of images.
Since removing an image updates the index (and hence the React key) for the following ones, React will rerender all of them.
If you don't want to rerender them, try using something else as a key (for example the image url)
See more here: https://facebook.github.io/react/docs/reconciliation.html#keys
Upvotes: 3