Updating an object in the ngrx/store

前端 未结 4 1641
無奈伤痛
無奈伤痛 2021-01-04 21:52

I\'m using @ngrx/store for an Angular 2 app.

My store holds a list of say, Book objects. I want to update a field in one of those objects. I also happ

4条回答
  •  心在旅途
    2021-01-04 22:22

    As already mentioned - the reason you are getting

    Cannot assign to read only property 'name' of object

    is because 'ngrx-store-freeze' freezes the state and prevents mutating it.

    Object.assign will provide a new object as you expect, but it will copy the state's properties along with each property's own definition - such as the 'writable' definition (which 'ngrx-store-freeze' likely sets to false).

    A different approach is described in this answer and explains how cloning objects with JSON.parse(JSON.stringify(yourObject)) as fastest, but this approach has flaws if you keep dates or methods etc' in your state.

    using lodash's 'cloneDeep' is probably your best bet for deep cloning the state.

提交回复
热议问题