简体   繁体   中英

React : update one value of my state in reducer

I try to modify a value of my current state with redux. Here my state :

tickets : {
    high_tickets: [
        {
            "value": value,
            "value": value,
            "value": value,
            "value": value,
            "visibility": 1
        },
        {
             ...
        }
    ],
    low_tickets: [
        ...
    ]
}

Here my ticket reducer :

case 'HIDE_TICKET':
      const i = action.index
      if(action.typeFraud == "high") {
        state = {
          "high_tickets": [
            ...state.high_tickets.slice(0,i),
            {
              ...state.high_tickets[i],
              "visibility": 0
            }
            ...state.high_tickets.slice(i + 1),
          ],
          "low_tickets": [
            ...state.low_tickets
          ]
        }
      }
      else if(action.typeFraud == "low") {
        ...
      }
      return state
      break;

I have an error at the line {...state.high_tickets[i],"visibility": 0} . Unexpected tocken.

How can I modify only one value of my object and not redifine all values in my reducer.

Thanks.

You can use Object.assign(state.high_tickets[i], { visibility: 0 }) if you want to mutate the existing object, or Object.assign({}, state.high_tickets[i], { visibility: 0 }) if you want to create an entirely new object.

It will look like:

"high_tickets": [
    ...state.high_tickets.slice(0,i),
    Object.assign(...),
    ...state.high_tickets.slice(i + 1),
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM