how can I make a copy of deeply nested state?

This question already has an answer here:

  • How do I correctly clone a JavaScript object? 54 answers

  • There are a couple of options:

  • Use the update immutability helper which has some excellent docs on the React site,
  • Use a package like clone which is optimised for this kind of thing.
  • I'd recommend the first as the syntax is particularly powerful, especially when dealing with large structures like a Redux store.

    As an example from the docs:

    import update from 'immutability-helper';
    
    const newData = update(myData, {
      x: {y: {z: {$set: 7}}},
      a: {b: {$push: [9]}}
    });
    

    Allows you to modify deeply-nested properties without worrying about dangerous mutations on existing objects.


    The easiest shortcut for that is:

    const clone = JSON.parse(JSON.stringify(state));
    

    All in all that involves the problem of cloning an object, there are couple of answers on that topic out there, depending on stuff like:

  • are there function references in the source object,
  • are there dom elements involved,
  • Date objects,
  • and more…
  • But in that case, you are dealing with a »plain json Object«, since it is the redux state, so the method above will work.

    Another way would be an recursive function which copies all the nested data, but as mentioned above, in this case you do not have to do it, since you dont have to worry about dom elements or other stuff alike.

    链接地址: http://www.djcxy.com/p/24782.html

    上一篇: 如何创建一个示例(匿名)R脚本来提供可重现的示例?

    下一篇: 我怎样才能做一个深度嵌套状态的副本?