当存储初始状态为数组时,如何实现reducer?

laawzig2  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(306)

我试图理解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减速器的唯一工作方法是添加todo,无法确定如何删除todo,如何继续和todo工作。我在removetodo收到一个typeerror,上面写着“无法读取未定义的属性'filter'”。。。以及来自另外两个方法的未定义返回。你们能帮我个忙吗?提前问候,请忘记我糟糕的语法和编码

ohtdti5x

ohtdti5x1#

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

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

rm5edbpk2#

你错过了 return 在其他情况下,您不需要将每个属性指定给 action.payload 照原样传过去,这就是它的样子

const todos = (state = initialState, action) => {
  switch (action.type) {
    case "AddTodo":
      return [...state, action.payload];

    case "RemoveTodo":
      return state.todos.filter((todo) => todo.id !== action.id)

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

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

    default:
      return state;
  }
};

相关问题