首页 > 解决方案 > React js reducer 逻辑条件

问题描述

使用下面的代码过滤器选项。我知道它是如何工作的过滤方法。这里我怀疑'DELETE_NOTE'的逻辑陈述。note.id 将保存 id 号 0,1,2...我怀疑 action.payload 对条件做了什么。它会保存像 id 1,2,3 这样的数字吗?请清除它。

export default function reducer(state, action) {
 switch(action.type) {
     case 'SET_CURRENT_NOTE':
         return {
             ...state,
             currentNote: action.payload
         }
         case 'DELETE_NOTE':
           const deleteNotes = state.notes.filter(
               note => note.id !== action.payload
           )
           return {
               state,
               notes: deleteNotes
           }
     default:
         return state;
 }
}

标签: reactjsfilterreact-hooksconditional-statements

解决方案


在删除注释时,您将使用如下所示的有效负载调度DELETE_NOTE操作。note Id

dispatch({ type: 'DELETE_NOTE', payload: 3}); - 这里的有效载荷只不过是要删除的笔记的 id。

在reducer函数中,过滤除已删除的note Id之外的所有状态下的note,并返回更新后的状态。

case 'DELETE_NOTE':
           const deleteNotes = state.notes.filter(
               note => note.id !== action.payload // here payload will be 3
           )
           return {
               ...state,
               notes: deleteNotes
           }

推荐阅读