javascript - 存储初始状态为数组时如何实现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,上面写着“无法读取未定义的属性‘过滤器’”......并且未定义的返回来自另外两种方法。你们能给我一些帮助吗?提前问候,请忘记我糟糕的语法和编码
解决方案
在您的情况下, state 是一个数组,因此state.todos将是未定义的。您可以使用类似的方法修复“RemoveTodo”案例
case 'RemoveTodo':
return state.filter(todo => todo.id !== action.payload)
推荐阅读
- flutter - 如何使用 GoogleMaps 在 PlacePicker 中将当前位置设置为 initialPosition - Flutter
- sql-server - 在 SQL FILESTREAM 上保存 docx 时 Word 显示错误消息
- javascript - 这里地图动态更改地图控件的语言
- java - 如何从 https://rbs.indianrail.gov.in/ShortPath/ShortPath.jsp 抓取火车路线数据
- android - AdMob 自适应横幅未在 Jetpack Compose 中显示
- python - 进口是在主要功能中还是在陈述中?
- javascript - Vuejs 3 - 组件内的数据功能问题
- c# - 为客户端服务器身份验证寻找 SSLStream.AuthenticateAsClient() 的替代方法
- javascript - 如何在常量或变量中返回使用 Express 和 Edge JS 呈现的视图?
- reactjs - 上下文 API 状态正在返回 JSON 意外错误