最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Spread Operator Dynamic Properties Update - Stack Overflow

programmeradmin2浏览0评论

I have a state that looks like this:

state: {
    1: {show: false, description: 'one'},
    2: {show: false, description: 'two'},
    3: {show: true, description: 'three'}
   }

Depending on a variable "id" that comes from the action, I have to update the state.

Something like this:

var returnedState = {...state, [id].show : ![id].show}

How can I do this?

I have a state that looks like this:

state: {
    1: {show: false, description: 'one'},
    2: {show: false, description: 'two'},
    3: {show: true, description: 'three'}
   }

Depending on a variable "id" that comes from the action, I have to update the state.

Something like this:

var returnedState = {...state, [id].show : ![id].show}

How can I do this?

Share Improve this question edited Jan 27, 2017 at 13:45 Diego Unanue asked Jan 26, 2017 at 20:47 Diego UnanueDiego Unanue 6,8269 gold badges48 silver badges69 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 17
{...state,
 [id]: {
  show: !state[id].show 
 }
}

that will copy the original state and then toggle the show value for the specific key/id that came from the action.

Here is a working code pen http://codepen.io/finalfreq/pen/mRBjZV

The previous answer was correct but just leaves the show property on the sub object, removing the other ones. To keep all properties and change the property you want you have to use:

 {...state, [id] : {...state[id], show: !state[id].show}}

Have to add ...state[id]

this.setState(prevState => ({
...state,
state[id]: !prevState[id].show
}))

Here you have to take last state as prevState and then update the object with supplied key with opposite value of previous state's object.

发布评论

评论列表(0)

  1. 暂无评论