简体   繁体   English

如何从 Redux 状态中删除特定项目?

[英]How to delete specific item from Redux state?

When I click delete I get the Can not read property 'id' of null error.当我点击删除时,我得到了错误的无法读取属性“id” I am confused.* How to pass the id so only the component I clicked on (delete button) is removed?**我很困惑。* 如何传递 id 以便仅删除我单击的组件(删除按钮)?**

Reducer:减速器:


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
  }
}

Action行动

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

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

Component成分

   <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' })

Based on your current implementation, you need to pass note id to根据您当前的实现,您需要将注释 id 传递给

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

Also, in reducer, you need to return modified state.此外,在减速器中,您需要返回修改后的状态。

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

As an advice, you actually don't use actions you defined, because you directly dispatch with type.作为建议,您实际上不使用您定义的操作,因为您直接使用类型调度。 So, keep in mind that it's a better approach to write actions and fire them using mapDispatchToProps .因此,请记住,使用mapDispatchToProps编写操作并触发它们是一种更好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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