【发布时间】: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