Right way to clone objects / arrays during setState in React

前端 未结 4 1265
温柔的废话
温柔的废话 2021-02-20 10:36

I start with:

constructor() {
   super();
      this.state = {
         lists: [\'Dogs\',\'Cats\'], 
         items: {Dogs: [{name: \"Snoopy\"}, {name: \"Lola\"         


        
4条回答
  •  忘了有多久
    2021-02-20 11:08

    One issue might be that var allItems = {...this.state.items}; will only do a shallow clone of this.state.items. So when you push data into this array, it will change the existing array before you call setState.

    You could use Immutable.js to solve this issue.

    import { List, fromJS, Map } from 'immutable';
    
    constructor() {
       super();
          this.state = {
           lists: List(['Dogs','Cats']), 
           items: fromJS({
            Dogs: [
              { name: "Snoopy" },
              ...
            ],
            Cats: [
              { name: "Felidae" },
              ...
            ]
          })
       };
    }
    

    and then your add function would be as follow:

    handleAddItem(s) {      
      var key = Object.keys(s)[0];
      var value = s[key];
    
      var allItems = this.state.items.set(key, Map({ name: value }));
      this.setState({ items: allItems });
    }
    

    Just a thought!

提交回复
热议问题