首页 > 解决方案 > 如何从 Redux 状态中删除特定项目?

问题描述

当我单击删除时,我得到Can not read property 'id' of null错误。我很困惑。*如何传递 id 以便仅删除我单击的组件(删除按钮)?**

减速器:


const notesReducer = (state = notes, action, id) => {
  switch (action.type) {
    case 'ADD':
      return [...state, action.newItem]

    case 'DELETING':
      //const newState = [...state.filter((note) => note !== action.note)]
      const newState = [...state]
      newState.filter((note) => note.id !== action.payload.id)
    //newNote.pop()

    default:
      return state
  }
}

行动

export const add = (id) => {
  return {
    type: 'ADD',
  }
}

export const deleting = (id) => {
  return {
    type: 'DELETING',
  }
}

零件

   <div>
          {notes.map((item, index) => (
            <div>
              <Select></Select>
              <Dialog key={uuid()}></Dialog>
              <Button
                key={uuid()}
                onClick={deleteNote}
              >
                Delete
              </Button>
            </div>
          ))}
        </div>
dispatch({ type: 'ADD', mynote }),
dispatch({ type: 'DELETING' })

标签: javascriptreactjsreduxjsx

解决方案


根据您当前的实现,您需要将注释 id 传递给

dispatch({ type: 'DELETING', note.id })

此外,在 reducer 中,您需要返回修改后的状态。

    case 'DELETING':
      return state.filter((note) => note.id !== id)

作为建议,您实际上不使用您定义的操作,因为您直接使用类型进行调度。因此,请记住,使用mapDispatchToProps.


推荐阅读