javascript - React-Redux:如何从数组中添加每个项目
问题描述
我当前的调度实现
我尝试通过映射来调度项目,但有时 Redux 会给出未定义的错误,所以我想在 reducer 中尝试更好的方法。
const dispatch = useDispatch()
const mapCheck = [
"Math",
"Spanish",
"Clean garden",
]
mapCheck.map(c=>dispatch(createCustomList(c.val)))
我想要做什么
我正在尝试从数组中获取每个单独的项目以进行分派,但是我得到了这个输出我有一个待办事项列表,我在其中分派了一个数组,如下所示:
我的减速机
import { CUSTOM_LIST } from "../actions/shoppingList";
const initialState = {
myCustomItems: []
};
const ToDoReducer = (state = initialState, action) => {
switch (action.type) {
case CUSTOM_LIST:
const customList = { id: Date.now(),val: action.custom.custom};
const custom = state.myCustomItems.concat(customList);
const existingCustomItem = state.myCustomItems.findIndex(
item => item.val === action.custom.custom
);
if (existingCustomItem >= 0) {
return {...state, myCustomItems: state.myCustomItems}
} else {
return {...state,myCustomItems: custom};
}
default:
return state;
}
};
export default ToDoReducer;
期望的输出
如何映射每个项目并在所需输出中添加如下所示的 id。不用担心 id 只是Date.now()
所需的输出:
const DesiredOutput = [{
"id": "qm6a67ci",
"val": "Math",
},
{
"id": "qm6a62ci",
"val": "Spanish",
},
{
"id": "rkrkmroepe",
"val": "Clean garden",
}
]
解决方案
请使用以下代码。希望它能解决您的问题。
import { CUSTOM_LIST } from "../actions/shoppingList";
const initialState = {
myCustomItems: []
};
const ToDoReducer = (state = initialState, action) => {
switch (action.type) {
case CUSTOM_LIST:
const customList = { id: Date.now(),val: action.custom.custom};
const existingCustomItem = state.myCustomItems.findIndex(
item => item.val === action.custom.custom
);
if (existingCustomItem > -1) {
return {...state, myCustomItems: state.myCustomItems}
} else {
return {...state,myCustomItems: [...state.myCustomItems,customList ]};
}
default:
return state;
}
};
export default ToDoReducer;
或者您可以做的第二种方法是,您可以分派单个动作,而不是分派多个动作
下面的代码将从数组中删除重复项,因此您不必在减速器中添加条件
const dispatch = useDispatch()
const mapCheck = [
"Math",
"Spanish",
"Clean garden",
]
dispatch(createCustomList[...new Set(mapCheck)]))
减速机文件
import { CUSTOM_LIST } from "../actions/shoppingList";
const initialState = {
myCustomItems: [],
};
const ToDoReducer = (state = initialState, action) => {
switch (action.type) {
case CUSTOM_LIST:
return {
...state,
myCustomItems: action.customList.map((val) => ({
id: Date.now(),
val,
})),
};
default:
return state;
}
};
export default ToDoReducer;
推荐阅读
- angular - 无法从嵌套角度表单中的子组件获取更改
- google-colaboratory - 如何从谷歌驱动器将一个大数据集cp到colab
- java - 在 java 中创建 BufferedImage 数组时出错
- javascript - 为什么无法从 redux 读取我的 properties 属性?
- node.js - 使用对象数组过滤字符串文档
- google-chrome - 可轻松编辑本地存储的 Chrome 扩展程序
- azure-devops - 在 Azure 文件副本中,您可以将副本复制到根容器中吗?
- python - 如何加速 Python 中的顺序二进制写入
- javascript - React.js 在 useState 设置默认值之前运行 useEffect
- c++ - 如何在自己的成员函数中重置 C++ 类