首页 > 解决方案 > 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)

标签: reactjs

解决方案


如果没有您的特定数据,很难对此进行测试,但这应该可以:

  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)

推荐阅读