Updating the array object in React state using immutability helper

匿名 (未验证) 提交于 2019-12-03 02:16:02

问题:

I am updating an object within an array in React state using immutability helper.

The object I want to modify is nested:

this.state = {   a: {     b: [{ c: '', d: ''}, ...]   } }  

I want to update the prop c within the nth element of b using immutability helper.

The equivalent code without the immutability helper is:

const newState = Object.assign({}, this.state); newState.a = Object.assign({}, newState.a); newState.a.b = newState.a.b.slice(); newState.a.b[n] = Object.assign({}, newState.a.b[n]); newState.a.b[n].c = 'new value'; this.setState({ newState }); 

I know the above code is a bit ugly. I am assuming the code using immutability helper will solve my problem. Thanks

回答1:

One way to do it would be using $set

let index = 0; let newState = update(this.state, {    a: {      b: {       [index]: {                c: { $set: "new value"}        }     }   } }); this.setState(newState); 

jsfiddle



回答2:

Im importing update from immutability helper here :)

this.state = {   a: {     b: [{ c: '', d: ''}, ...]   } }    this.setState((prevState, props) => update(prevState, {     a: {         b: {             $apply: b => b.map((item, ii) => {                 if(ii !== n) return item;                 return {                     ...item,                     c: 'new value'                 }             })         }     } })) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!