What is the best way to mutate a complex state in React.js?

Here's a simple React component that displays a list, when a list item gets clicked, the element adds a class name with a name selected.

var CX = React.addons.classSet;
var List = React.createClass({
  getInitialState: function(){
    return {
      items: this.props.items
    }
  },

  handleItemClick: function(item){
    item.isSelected = true;
    //hack
    this.forceUpdate();
  },

  render: function(){
    var self = this;
    var items = this.state.items.map(function(item, index){
      var className = CX({
        'item': true,
        'selected': item.isSelected
      });
      return (
        <li key={index} 
            onClick={self.handleItemClick.bind(self, item)}
            className={className}>
            item.name
        </li>
      );
    });

    return (
      <ul>
        {items}
      </ul>
    );
  }
});

var items = [{
  name: 'Apple',
  value: 1
}, {
  name: 'Microsoft',
  value: 2
}];

React.renderComponent(<List items={items} />, document.body);

Question: because it stateis a reference type that contains an array of an object, and in the event handler handleItemClickI get only the corresponding one item. I am currently mutating itemdirectly, then invoking this.forceUpdate(), the result will be as expected.

However, as the React documentation suggests, mutating statedirectly is bad behavior, and I come across another method that uses React.addons.updateto mutate a complex object, but I didn't get it working.

, - , ? !

React.addons.update

+4
1

( React.addons.update), ,

var index = this.state.items.indexOf(item);
var mutation = {}; // can't have dynamic keys in object literals :( [ yet :) ]
mutation[index] = {isSelected: {$set: true}};
var newData = React.addons.update(this.state.items, mutation);
// `mutation` looks something like
// {0: {isSelected: {$set: true}}}
// i.e. set `isSelected` of the element at index 0 to true

, .

+7

All Articles