reactjs - useReducer 逻辑负责处理表中的 dublican
问题描述
我正在学习使用 useReducer。我在反应输入中写道,单击按钮后,将一个元素添加到表格并显示在页面上,我还想添加一个逻辑,不允许将两个具有相同内容的相同元素添加到表格中,但不幸的是它不起作用,请帮助。console.log 有效,但无论如何都会向数组中添加一个项目
const tab = []
const App = () => {
const [state, dispatch] = useReducer(
(state, action) => {
switch (action.type) {
case 'ADD':
for (const n of state) {
if (n.name === action.course.name) {
console.log('repeated text')
return
}
}
return [...state, action.course]
}
}, tab)
解决方案
如果没有您的特定数据,很难对此进行测试,但这应该可以:
const [state, dispatch] = useReducer(
(state, action) => {
switch (action.type) {
case 'ADD':
if(state.find(i => i.name === action.course.name))
return state
else
return [...state, action.course]
}
}, tab)
推荐阅读
- html - 即使单击网页上的其他位置,如何不失去对元素的关注?
- java - 我如何在 choco 求解器中获得变量总和
- wamp - 每次我重新启动 Surface 时 WAMP 服务器都不会变绿
- python - 以更有效的方式访问 3D 矩阵的所有奇数索引
- azure - Azure Active Directory 非管理员用户访问 Azure SQL 数据库
- c# - Json 反序列化失败
- python - 最后一个子图中缺少标题
- c - 如何逐条执行反汇编的ELF指令?
- oracle - 更新语句错误 - 删除任何非确定性 where 子句并重新发出 dml
- python - 打开 file.txt 并使用 argparse 存储到变量中