单击删除时,出现 无法读取null的属性'id' 错误。 我很困惑。*如何传递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' })
答案 0 :(得分:1)
根据您当前的实施方式,您需要将注释ID传递给
dispatch({ type: 'DELETING', note.id })
此外,在reducer中,您需要返回修改后的状态。
case 'DELETING':
return state.filter((note) => note.id !== id)
作为建议,您实际上不使用定义的操作,因为您直接使用type进行分派。因此,请记住,这是编写动作并使用mapDispatchToProps
触发动作的更好方法。