【问题标题】:How to properly check the current Index of an array in a React map?如何正确检查 React 映射中数组的当前索引?
【发布时间】: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


    【解决方案1】:

    您正在根据index 值而不是实际的id 在数组中设置对象。建议大量将 id 合并到每个对象中,然后通过 id 抓取对象来操作它。否则,您在操作数组时可能会遇到错误和意外行为。

    与使用map 时不使用数组索引的概念相同:这是一种反模式。

    https://reactjs.org/docs/lists-and-keys.html

    【讨论】:

    • 好吧,数组没有任何实际价值 atm 甚至 id 什么都没有,我的想法是只给所有东西 1,因为数量总是从 1 开始,然后通过加号单独更改/minus 函数(我很确定通过阅读这似乎不是一个好习惯)
    【解决方案2】:

    这是.map函数的第二个参数所以:

    libros.map((l, idx)
    

    idx 是你的i

    这里是documentation 关于它

    【讨论】:

    • 哦,我现在感觉自己像个小丑。快速提问我如何通过按钮发送 ID,因为是的,我现在有 id,但是我如何将它发送到按钮,所以它只更改 id &lt;button onClick = {plus, id}/&gt; 不起作用我虽然我会发送 id 作为参数对于const plus 函数
    • @ReactPotato 它应该是 onClick = {() =&gt; plus(id)} 所以点击你正在执行的加号函数以 id 作为参数
    • @ReactPotato 只是为了说明清楚,它是 index 而不是 id
    • 正确索引是的原因是位置而不是 ID,有没有办法让所有值都以 1 开头?因为如果我在一开始就声明只有第一个以 1 开头,如果我这样做:{cantidad[1, index]} 所有这些都保持空白
    • @ReactPotato 我认为您应该花时间阅读arraysmap 上的文档。
    猜你喜欢
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 2012-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多