javascript - How do I update an array for a React component? -
i have found react not update component when element in array changed. instead, new array must cloned , put in place.
for example, have array of _suggestedpeople
. when ui element representing 1 of these people clicked, i'd register calling selectperson
.
i expect react update after doing this:
selectperson: function(personid, selected) { var person = _.find(_suggestedpeople, {id: personid}); if (person) { person.selected = selected; } return person; },
however, end doing instead, seems unnecessary:
selectperson: function(personid, selected) { var index = _.findindex(_suggestedpeople, {id: personid}); var found = index !== -1; if (found) { var people = _.clonedeep(_suggestedpeople); people[index].selected = selected; _suggestedpeople = people; } return found; },
is latter correct way update array data of react component? or missing something?
you don't appear using react's built in state management. if do, middle ground between 2 approaches of updating state work. component re-render when it's state or properties change @ all.
initialise components state implementing
getinitialstate: function () { var whereveritcomesfrom = [ {id: 1, selected: false}, {id: 2, selected: false} ]; return { suggestedpeople: whereveritcomesfrom } }
your render method renders this:
render: function () { var _this = this; var peeps = this.state.suggestedpeople.map(function(person, index){ return <label key={index}><input type='checkbox' checked={person.selected} value={person.id} onchange={_this.handlepersonclick}/>{person.id}</label>; }); return <div>{peeps}</div>; },
handlepersonclick can merge of methods:
handlepersonclick: function(e) { var selectedid = e.target.value; var checked = e.target.checked; var peeps = this.state.suggestedpeople; var index = _.findindex(peeps, {id: selectedid}); peeps[index].selected = checked; this.setstate({suggestedpeople: peeps});
}
full jsfiddle
Comments
Post a Comment