javascript - 如何从 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' })
解决方案
根据您当前的实现,您需要将注释 id 传递给
dispatch({ type: 'DELETING', note.id })
此外,在 reducer 中,您需要返回修改后的状态。
case 'DELETING':
return state.filter((note) => note.id !== id)
作为建议,您实际上不使用您定义的操作,因为您直接使用类型进行调度。因此,请记住,使用mapDispatchToProps
.
推荐阅读
- google-sheets - 有没有办法过滤或查询唯一性由一列确定但返回所有列的唯一结果?
- python-3.x - TypeError:无法在 cplex 中腌制调用 mdl.solve() 的 dict_keys 对象
- vue.js - 如何在图表中保存用于构建图表数据标签的数组中元素的原始 ID?
- wpf - 有没有办法在设计时查看 DropShadowEffect?
- google-chrome - Win 10 升级后无法使用 Chrome、Firefox 访问互联网,但 Edge 工作正常
- google-maps - Google Geocoding API - 获取房子前面街道的纬度而不是屋顶
- python - 是否可以从操作系统的 af .mkv 和 .mp4 文件中获取时间长度
- flutter - 在 TextField Flutter 中垂直居中对齐文本
- sql - 数据动态分组|| 需要 SQL 查询
- c++ - How using lambda to make std::invoke lazy evaluation?