【问题标题】:map and count quantity in react在反应中映射和计数数量
【发布时间】:2022-11-28 19:22:30
【问题描述】:

我有一个关于用户添加到购物篮的文章列表的视图。

在每篇文章中,我都有一个增量/减量按钮来编辑数量。 递增/递减按钮正在工作,因为每次我的用户更改数量时它都会在我的数组中添加一个新对象

现在,我只有一个“+”和“-”按钮,但我想查看数量

我在想什么:

  • 获取所有文章列表并计算 useEffect 中的重复项(每次文章列表发生变化时)
  • 使用 useState 对象设置文章 ID 和数量

计算每件物品的单独数量的最佳方法是什么?

这是我的组件,带有文章映射和递增/递减按钮

   import React from 'react';
    import { Table } from 'react-bootstrap';
    import { useFieldArray } from 'react-hook-form';
    
    export const ListArticle = ({ watch, control }) => {
      const list = watch('Articles');

      //listWithoutDuplicates is because i just want to see once my articles even if the quantity is more than 1
      const listWithoutDuplicates = list?.filter(
        (ele, ind) => ind === list?.findIndex((elem) => elem.name === ele.name)
      );
    
      const { append, remove } = useFieldArray({
        control,
        name: 'Articles',
      });
    
      const increment = (oneArticle) => {
        append(oneArticle);
      };
    
      const decrement = (oneArticle) => {
        remove(oneArticle);
      };
    
     
      return (
        <>
          <Table responsive>
            <thead>
              <tr>
                <th> Name </th>
                <th> Color</th>
                <th> Quantity </th>
              </tr>
            </thead>
            <tbody>
              {listWithoutDuplicates?.map((oneArticle, index) => {
                return (
                  <tr key={index}>
                    <td>
                      <span>{oneArticle?.name}</span>
                    </td>
                    <td>
                      <span>{oneArticle?.color}</span>
                    </td>
                    <td>
                      <button type="button" onClick={() => decrement(oneArticle)}>
                        -
                      </button>
                       <p> HERE MY QUANTITY </p>
                      <button type="button" onClick={() => increment(oneArticle)}>
                        +
                      </button>
              
                    </td>   
                  </tr>
                );
              })}
            </tbody> 
          </Table>
        </>
      );
    };

【问题讨论】:

  • 为什么不保存每篇文章的数量字段而不是存储多篇文章?
  • 也许我做错了,我这样做是因为我需要计算更多的东西(比如价格,而且如果文章名称出现两次以上,那么我会申请降低总价等)
  • 我是一名初级开发人员,所以我知道有时我编写的代码可能比我需要的多,而且我确定我可以优化它,但是当你独自编写代码时,很难看出什么可以更好
  • 那完全没问题。我要回答。
  • 这个问题是通过征求“最佳方式”来征求意见。请更改它,以便它是明确地使用证据来回答或考虑关闭它。

标签: javascript reactjs react-hook-form


【解决方案1】:

为什么不保存每篇文章的数量字段而不是存储多篇文章?

const { append, remove, update } = useFieldArray({
  control,
  name: 'Articles',
});

const getArticleIndex = (articleId) => {
  let index = -1;
  list.forEach((article, _index) => {
    if(article.id === articleId)
      index = _index;
  });
  return index;
}    

const increment = (oneArticle) => {
  const index = getArticleIndex(oneArticle.id);
  // Article has not been added before.
  if(index === -1) {
    append({...oneArticle, quantity: 1});
  // Article has been added before so we increase the quantity.
  } else {
    const newArticleData = {...list[index]};
    newArticleData.quantity += 1;
    update(index, newArticleData);
  }
};
    
const decrement = (oneArticle) => {
  const index = getArticleIndex(oneArticle.id);
  // It's the last quantity of the article so we should remove it from the list.
  if(list[index].quantity === 1) {
    remove(oneArticle);
  // It's not the last quantity of the article so we should decrease the quantity.
  } else {
    const newArticleData = {...list[index]};
    newArticleData.quantity -= 1;
    update(index, newArticleData);
  }
};

然后循环遍历列表数据,没有必要使用列表无重复了。

【讨论】:

    【解决方案2】:

    像这样使用...

      import React,{useState} from 'react';
        import { Table } from 'react-bootstrap';
        import { useFieldArray } from 'react-hook-form';
        
        export const ListArticle = ({ watch, control }) => {
          const [list, setList] = useState(watch('Articles'));
        
          //listWithoutDuplicates is because i just want to see once my articles even if the quantity is more than 1
          //const listWithoutDuplicates = list?.filter(
           // (ele, ind) => ind === list?.findIndex((elem) => elem.name === ele.name)
         // );
        
          const { append, remove } = useFieldArray({
            control,
            name: 'Articles',
          });
        
          const increment = (index) => {
           //append(oneArticle);
        let newList =list;
        newList[index].quantity =(newList[index].quantity || 0) +1
        setList(newList)
          };
        
          const decrement = (index) => {
            //remove(oneArticle);
        let newList =list;
        newList[index].quantity =(newList[index].quantity || 0) -1
        setList(newList)
          };
        
         
          return (
            <>
              <Table responsive>
                <thead>
                  <tr>
                    <th> Name </th>
                    <th> Color</th>
                    <th> Quantity </th>
                  </tr>
                </thead>
                <tbody>
                  {list?.map((oneArticle, index) => {
                    return (
                      <tr key={index}>
                        <td>
                          <span>{oneArticle?.name}</span>
                        </td>
                        <td>
                          <span>{oneArticle?.color}</span>
                        </td>
                        <td>
                          <button type="button" onClick={() => decrement(index)}>
                            -
                          </button>
                           <p>{oneArticle.quantity || 0}</p>
                          <button type="button" onClick={() => increment(index)}>
                            +
                          </button>
                  
                        </td>   
                      </tr>
                    );
                  })}
                </tbody> 
              </Table>
            </>
          );
    };
    

    我希望这能帮到您!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-20
      • 2019-05-17
      • 2021-02-27
      • 2020-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多