jeudi 5 février 2015

ReactJS Simple Add / Remove Component Pattern

I'm quite confused about this pattern in React. I have seen it in other places it but it does not seem correct.


Given the below code:



/** @jsx React.DOM */

var React = window.React = require('react'),
Item = require("./ui/Item");

var ItemApp = React.createClass({
getInitialState: function() {
return {
items: [ "Example Item" ] // we want one thing to render initially
}; // so prepopulate with one thing
},
getDefaultProps: function () {
return {
index: 1
}
},
onAddItem: function (e) {
var debts = this.state.debts.push( "New Item " + this.props.index);
this.setState({ items: this.state.items });
this.props.index++;
},
onRemoveItem: function (i) {
// splice here
this.state.items.splice(i, 1);
this.setState({ items: this.state.items });
this.props.index--;
},
render: function () {
var items = this.state.items;
var closeFn = this.onRemoveItem;
return (
<div className="col-lg-12">
<div className="cold-md-3"></div>
<div className="col-md-3 col-md-offset-9">
<button type="button" className="btn btn-default" onClick={this.onAddItem}><span className="glyphicon glyphicon-plus"></span> Add New Debt</button>
</div>
{items.map(function (item, i) {
return <Item name={item} closeFn={closeFn.bind(null, i)} key={i} />;
})}
</div>
);
}
});


The example above works like intended (it's a list and you can add and remove things at will) however whenever I add something renders the whole thing over again.


So after only adding one component the whole thing has rendered 3 times. After clicking twice it will have rendered 5 times. You can see why this might be a problem.


This seems really inefficient is there a better way to do this?


Aucun commentaire:

Enregistrer un commentaire