2017-01-02 27 views
3

我試圖使用delete按鈕。我做這樣的爲什麼拼接在反應中不能正確工作?

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

    return state 

我的列表中刪除的行,但它不會刪除該行。這裏是我的代碼 https://plnkr.co/edit/bpSGPLLoDZcofV4DYxPe?p=preview 實際使用添加按鈕我生成列表的項目,並有刪除按鈕我試圖從列表中刪除項目使用delete button 你能告訴我爲什麼它不工作?

回答

5

當在React或Redux中處理狀態時,請避免使用Array#splice。這會改變你的狀態,你永遠不想這樣做。相反,支持像Array#slice這樣的不可改變的方法。例如

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

在ES6最後一行也可以寫爲:

return [...state.slice(0, index), ...state.slice(index + 1)];