Javascript 如何从Redux状态删除特定项?
单击“删除”时,我会出现无法读取null属性“id”的错误。 我很困惑。*如何传递id以便只删除我单击的组件(删除按钮)** 减速器:Javascript 如何从Redux状态删除特定项?,javascript,reactjs,redux,jsx,Javascript,Reactjs,Redux,Jsx,单击“删除”时,我会出现无法读取null属性“id”的错误。 我很困惑。*如何传递id以便只删除我单击的组件(删除按钮)** 减速器: const notesReducer = (state = notes, action, id) => { switch (action.type) { case 'ADD': return [...state, action.newItem] case 'DELETING': //const newStat
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>
根据您当前的实现,您需要将note id传递给
dispatch({ type: 'DELETING', note.id })
此外,在reducer中,您需要返回修改状态
case 'DELETING':
return state.filter((note) => note.id !== id)
作为建议,您实际上不使用您定义的操作,因为您直接使用类型分派。因此,请记住,编写操作并使用
mapDispatchToProps
触发操作是一种更好的方法。您的deleteNote
方法是什么样的?该方法仅为:dispatch({type:'DELETING'})。
case 'DELETING':
return state.filter((note) => note.id !== id)