Question: why splice not working correctly in react?

Question

why splice not working correctly in react?

Answers 1
Added at 2017-01-02 01:01
Tags
Question

I am trying to delete row from my list using delete button .I do like this

if (state.indexOf(action.payload) > -1) {
      console.log('iff----')
        state.splice(state.indexOf(action.payload), 1);
    }
          console.log(state)

     return state

but it is not deleting the row .here is my code https://plnkr.co/edit/bpSGPLLoDZcofV4DYxPe?p=preview Actually using add button I am generating the list of item and there is delete button I am trying to delete item from list using delete button could you please tell me why it is not working ?

Answers
nr: #1 dodano: 2017-01-02 02:01

Avoid using Array#splice when working with state in React or Redux. This mutates your state, which you never want to do. Instead, favour immutable methods like Array#slice. e.g.

const index = state.indexOf(action.payload);
if (index === -1) {
  return state;
}
return state.slice(0, index).concat(state.slice(index + 1));

In ES6 that last line could also be written as:

return [...state.slice(0, index), ...state.slice(index + 1)];
Source Show
◀ Wstecz