首页 > 解决方案 > 存储初始状态为数组时如何实现Reducer?

问题描述

我试图了解 React-Redux 基础知识,但我陷入了这种特殊情况:

我的代码操作:


let todoId = 1

export const ADDTODO = 'AddTodo'
export const REMOVETODO = 'RemoveTodo'
export const TOINPROGRESS = 'ToInProgress'
export const TODONE = 'ToDone'

export function addTodo(payload){
return{
   type: ADDTODO,
   payload:{
      status: 'Todo',
      id: todoId++,
      title: payload.title,
      date:payload.date,
      description:payload.description,
      place:payload.place     
        }                                
    }       
}

export function removeTodo(todoId){
    return{
        type: REMOVETODO,
        payload:todoId
    }
}

export function toInProgress(todoId){
    return{
        type: TOINPROGRESS,
        payload:todoId
    }
}

export function toDone(todoId){
    return{
        type: TODONE,
        payload:todoId
    }
}

我尝试减少代码:


import { addTodo, removeTodo, toInProgress, toDone } from '../actions';
const initialState = [];

const todos = (state = initialState, action) => {
  switch(action.type) {   
      case 'AddTodo':      
        return[
          ...state, {           
            date:action.payload.date,
            description:action.payload.description,
            id:action.payload.id,
            place:action.payload.place,
            status:action.payload.status,
            title:action.payload.title,
            
          }          
        ]  
       
 case 'RemoveTodo':
     console.log(state)            
     return {
         ...state,
         todos: state.todos.filter(todo => todo.id  !== action.id)
     }


               
 case 'ToInProgress':             
     state.map(todo =>(todo.id===action.id)?{...todo,status:"InProgress"}:todo)     
         
 case 'ToDone':    
     state.map(todo =>(todo.id===action.id)?{...todo,status:"Done"}:todo)
                  
 default: 
     return state
  }
}

todos reducer 的唯一工作方法是 AddTodo,无法弄清楚 RemoveTodo、ToInProgress 和 ToDo 工作。我在 RemoveTodo 处收到一个 TypeError,上面写着“无法读取未定义的属性‘过滤器’”......并且未定义的返回来自另外两种方法。你们能给我一些帮助吗?提前问候,请忘记我糟糕的语法和编码

标签: javascriptreactjsreduxstate

解决方案


在您的情况下, state 是一个数组,因此state.todos将是未定义的。您可以使用类似的方法修复“RemoveTodo”案例

case 'RemoveTodo':          
    return state.filter(todo => todo.id  !== action.payload)

推荐阅读