javascript - ReactJS checkable list issue -
i'm trying create react component contains long list (~500 items) checkboxes opposite each item. should toggle checked state of each item , toggle checked state of items in list. implemented component, see that. solution has low performance , time lag when toggle checkbox. when integrated in page, work slower jsfiddle example.
what i'm doing wrong? should choose way work items data?
var hello = react.createclass({ getinitialstate: function () { var db = []; (var = 0, l = 100; < l; i++) { db.push({ name: math.random().tostring(36).replace(/[^a-z]+/g, '').substr(0, 5), value: }); } return { db: db }; }, checkall: function (ev) { var items = this.state.db.slice(); items.foreach(function (v) { v.checked = ev.target.checked; }); this.setstate({db: items}); }, handlecheck: function (ev) { debugger; var id = ev.target.dataset.id; var items = this.state.db.slice(); var item = items.filter(function (v) { return v.value == id; })[0]; item.checked = ev.target.checked; console.log(items.filter(function (v) { return v.checked; })); this.state({db: items}); }, render: function () { return <div> <table> <thead> <tr> <th>name</th> <th>value</th> <th> <input type="checkbox" onchange={this.handlecheck} id="check-all"/> <label htmlfor="check-all">check all</label> </th> </tr> </thead> <tbody> { this.state.db.map(function (v, i) { return ( <tr key={i}> <td>{v.name}</td> <td>{v.value}</td> <td> <input id={'item-'+i} type="checkbox" data-id={i} onchange={this.handlecheck} checked={v.checked}/> <label htmlfor={'item-'+i}>check this</label> </td> </tr> ); }.bind(this)) } </tbody> </table> </div>; } });
solution
i have many cells in table complex hierarchy. when toggle checkbox value, cells rerendered, including ones unchanged values, causes huge time lag. splited component small components shouldcomponentupdate
callbacks , works fine. help!
i've made improvements code: https://jsfiddle.net/lfbodh90/1/
what i've changed:
in event handler, can item index, speeding lookup time lot:
handlecheck: function (id) { var items = this.state.db; var item = items[id] item.checked = ev.target.checked; this.setstate({db: items}); }
another thing: when creating checkbox, can pass index parameter directly, using bind
:
<input id={'item-'+i} type="checkbox" onchange={this.handlecheck.bind(this, i)} checked={v.checked}/> <label htmlfor={'item-'+i}>check this</label>
i've removed slice
calls not necessary in example given.
i've increased number of items on jsfiddle above testing. when check/uncheck specific checkbox, it's fast.
hope helped
Comments
Post a Comment