Right way to clone objects / arrays during setState in React

前端 未结 4 1320
温柔的废话
温柔的废话 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:26

    I wanted to add a bit more info about cloning arrays. You can call slice, providing 0 as the first argument:

    const clone = myArray.slice(0);
    

    The code above creates clone of the original array; keep in mind that if objects exist in your array, the references are kept; i.e. the code above does not do a "deep" clone of the array contents.

提交回复
热议问题