【发布时间】:2021-11-12 15:20:06
【问题描述】:
我正在尝试增加特定位置的数组的值。假设你有一个数组:
const [cantidad, setCantidad] = useState([
{cantidadID: 1, value: 1},
{cantidadID: 2, value: 1},
{cantidadID: 3, value: 1}
]);
现在我想用一个按钮只改变其中一个的值(不管是哪一个)
const plus = (e) => {
setCantidad(cantidad[e] + 1);
};
const minus = (e) => {
if (cantidad[e] > 0){
setCantidad(cantidad[e] - 1);
} else {
window.alert("Sorry, Zero limit reached");
setCantidad(0);
}
};
e 是数组的索引(带有一些智能编码 ofc)从一个表发送,就像这样
{libros.map((l) => (
<tr>
<td>
<button onClick={mas} />
{cantidad}
<button onClick={menos} />
</td>
<td>{l.grado}</td>
<td>
<input
onChange={(event) => {
let checked = event.target.checked;
}}
type="checkbox"
checked=""
>
</input>
{l.descripcion}
</td>
<td>{l.editorial}</td>
<td>${parseFloat(l.precio).toFixed(2) * cantidad}</td>
</tr>
))}
// I know the checkbox is not working. I'm still working through that.
现在在我的脑海里,在映射时应该有一个变量控制cantidad 变量的索引,但如果我尝试在映射中创建一个新变量它会变得疯狂并且崩溃,(除非我格式错误或放在错误的地方)
所以我得到的逻辑很简单,但我不知道如何应用它,它会是这样的: 如果在映射时有 X[] 变量,请创建一个控制数组变量 ID 的 Y 变量,并且如果要从 X[] 更改特定值的值,则必须将 X[Y] 变量发送到按钮const plus 和 minus ,然后仅从该特定 ID 更改该变量。
在我的完整代码中,我没有使用 3 个值,顺便说一下,这些值等于从地图带来的数据量
感谢任何提示、数据或信息。如果您需要我的整个代码的实际输入,请告诉我,如果我不能让它工作,我可能会稍后发布代码。
这是我正在处理的实际代码,即使第一个问题得到了回答,我仍然对下一部分有问题(仅相关部分)
const [amount, setAmount] = useState([1]);
//I know this bit doesn't make sense (Yet) I'm trying to figure out first the first bit
const plus = (index) => {
setAmount(amount[index] + 1);
};
const menos = (index) => {
if (amount[index] > 0){
setAmount(amount[index] - 1);
}
else {
window.alert("Sorry, Zero limit reached");
setAmount(0);
}
};
{books.map((l, index) => (
<tr >
<td>
<button onClick = {() => plus(index)}/>
{amount[index]}
<button onClick = {() => minus(index)}/>
</td>
<td>{l.grado}</td>
<td >
<input onChange = {(event) => {
let checked = event.target.checked;
}}
type="checkbox" checked = "">
</input>
{l.descripcion}
</td>
<td >{l.editorial}</td>
<td >${parseFloat(l.precio).toFixed(2) * amount[index]}</td>
</tr>
))}
我知道在 Javascript 中你可以使用 Array(5).fill(2) 有没有类似的东西?就像我想做 Array(map.length).fill(1) 例如,所以值总是以 1 开头,然后我所要做的就是使用索引来改变正确的加减号。
【问题讨论】:
标签: arrays reactjs array.prototype.map