【问题标题】:How to fill an array with the same values X times and how to send the data correctly to a function?如何用相同的值填充数组 X 次以及如何将数据正确发送到函数?
【发布时间】:2021-09-17 22:14:37
【问题描述】:

我提出了一个与数组和地图相关的类似问题,但只有一半得到了回答,这就是我将这个分开的原因。

我有这个代码(只有相关信息):

const [libros, setLibros] = useState([]);
const [cantidad, setCantidad] = useState([1]);

//This is not finished because I'm still stuck
const mas = (index, value) => {
        setCantidad(cantidad[index] + 1);
      };

      const menos = (index, value) => {
        if (cantidad[index] > 0){
            setCantidad(cantidad[index] - 1);
        }
        else {
            window.alert("Sorry, Zero limit reached");
            setCantidad(0);
        }
      };


<tbody>
     {libros.map((l, index) => (
          <tr >
           <td>
               <button onClick = {() => mas(index)}/>
               {cantidad[index]}
               <button onClick = {() => menos(index)}/>
               </td>
               <td>{l.grado}</td>

               <td >
               <input onChange = {(event) => {
               let checked = event.target.checked;
               }} 
               type="checkbox" checked = "">

//I know this check is not working properly I'm strill trying to figure out this one 

               </input>
               {l.descripcion}
               </td>
               <td >{l.editorial}</td>
               <td >${parseFloat(l.precio).toFixed(2) * cantidad[index]}</td>
               </tr>

   ))}
</tbody>

我知道在 javascript 中您可以执行以下操作:

Array(5).fill(2)
//=> [2, 2, 2, 2, 2]

有没有办法在 React 中做类似的事情?因为我想要实现的是以下内容: “cantidad”将始终以 1 开头,然后授予用户根据他/她想要的项目数量更改该数量 +1 或 -1 的能力,但我不知道如何将所有值设置为 1话虽如此,在告诉我通过在地图上添加索引值我可以单独控制它们之前已经有人指导我我不明白如何在我的代码上应用它,因为我想发送当前索引和当前该索引的值为

const mas = (index, value) => {
        setCantidad(cantidad[index] + 1);
      };

      const menos = (index, value) => {
        if (cantidad[index] > 0){
            setCantidad(cantidad[index] - 1);
        }
        else {
            window.alert("Sorry, Zero limit reached");
            setCantidad(0);
        }
      };

我制作的函数,这就是打印 atm 的方式,如果您已经在数组中设置了 X 数量的值,但当值的数量基于数量时,我有点理解如何做到这一点地图重复的次数我尝试使用 map.lenght 但没有奏效欢迎任何建议/提示

这是完整的代码

import React, { useState, useEffect } from 'react'
import { auth, db } from './firebase';
import { useHistory } from 'react-router-dom';
import { Checkbox } from '@material-ui/core';

function CrearPedidos({user}) {
    const [libros, setLibros] = useState([]);
    const [cantidad, setCantidad] = useState(new Array(libros.length).fill(1);

    const history = useHistory("");
    const [totalPrice, setTotalPrice] = useState();

    const librosRef = db.collection('libros');
    const queryRef = librosRef.where('grado', '==', '4° Grado');

   console.log(queryRef)

    useEffect(() => {
        queryRef.orderBy("precio")
        .get()
        .then((snapshot) => {
              const tempData = [];
            snapshot.forEach((doc) => {
              const data = doc.data();
              tempData.push(data);
            });
            setLibros(tempData);
          });
      }, []);

      const mas = (index) => {
        setCantidad(cantidad[index] + 1);
      };

      const menos = (index) => {
        if (cantidad[index] > 0){
            setCantidad(cantidad[index] - 1);
        }
        else {
            window.alert("Sorry, Zero limit reached");
            setCantidad(0);
        }
      };

    return (
        <div className="listado_Pedidos"> 
        <div className="estudiantes_container">
            <h1 className = "estudiantes_container_h1">Estudiante: {user.displayName}</h1>
            <h1 className = "estudiantes_container_h1">Libros Nuevos</h1>
            <div className ="tableContainer">
            <table>
                <thead>
                    <tr className="Lista">
                        <th>Cantidad</th>
                        <th>Grado</th>
                        <th>Descripcion</th>
                        <th>Editorial</th>
                        <th>Precio</th>
                    </tr>
                </thead>
                <tbody>
                {libros.map((l, index) => (
                        
                        <tr >
                        
                        <td>
                            <button onClick = {() => mas(index)}/>
                            {cantidad[index]}
                            <button onClick = {() => menos(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) * cantidad[index]}</td>
                        </tr>

                     ))}
                </tbody>
            </table>
            </div>

            <div className="space" />
            <button onClick="{realizarPedidos}" className = "crear_estudiante_boton">Realizar Pedidos</button>
            <div className="space" />
      </div>

      </div>
    )
}

export default CrearPedidos

这就是它的样子以及 Cantidad 在日志上显示的内容

【问题讨论】:

  • 我注意到的第一件事是const [cantidad, setCantidad] = useState([1]),然后再往下一点:setCantidad(cantidad[index] + 1);。这是故意的吗?您将其初始化为数组 ([]),编号为 1,但随后您将类型更改为数字,而不是数组。
  • 呃,我在 React 中的编码技能并不是很粗糙/很差,所以我只是在尝试。

标签: arrays reactjs array-map


【解决方案1】:

您的setCantidad 方法使用需要设置一个包含递增值的新数组,而不是其中一项的递增值。

您正在使用数组初始化 useState,但后来将其从数组更改为数组中这些项目之一的值。

具体来说,您将cantidad 初始化为[1],这与new Array(1).fill(1) 相同。但是,您稍后将cantidad 设置为cantidad[index] + 1(假设index0)意味着您将cantidad[1] 更改为2。它从一个有数字的数组变成了一个数字。

为了将cantidad 保持为一个数组,您应该在它更改时使用一个新数组对其进行设置。 setCantidad 只是用来用新值更新您的状态;它不知道也不关心它是用什么初始化或以前设置的。

因此,您可以通过多种方式对其进行更新。这里有一个建议:

const mas = (index) => {
  cantidad[index] = cantidad[index]++
  // Note how we're setting it with a new array, not the original. 
  // It is important to know how JS references objects (such as arrays) vs other types 
  // by using its pointer as the source of truth vs its pure bytes, respectively
  setCantidad([...cantidad]);
};

const menos = (index, value) => {
  if (cantidad[index] > 0){
    cantidad[index] = cantidad[index]--
    setCantidad([...cantidad]);
  } else {
    window.alert("Sorry, Zero limit reached");
    // no need to do any setting here as the indexed value should already be zero based on the condition above
  }
};

【讨论】:

  • 哦,这就是一些人试图解释的内容,但我不明白他们将其设置回 1 而不是数组是什么意思,现在这很有意义。我只是有一个问题setCantidad([...cantidad]) 是什么意思?就像...cantidad 我是新来的反应所以......我无法理解一些基本的东西。任何文档链接都非常感谢。顺便说一句,我真的要为此提出一个问题,谢谢!
  • 这就是所谓的“解构赋值”,你可以在developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…阅读它是如何工作的详细信息
【解决方案2】:

你可以根据libros.length初始化cantidad数组

const [cantidad, setCantidad] = useState( new Array(libros.length).fill(1) );

const mas = (index) => {
  setCantidad(cantidad[index] + 1);
};

const menos = (index, value) => {
  if (cantidad[index] > 0){
    setCantidad(cantidad[index] - 1);
  } else {
    window.alert("Sorry, Zero limit reached");
    setCantidad(0);
  }
};

【讨论】:

  • 由于某种原因我不能使用 Array ,是不是因为我没有从 React.Component 扩展,如果是这样的话,还有其他解决方法吗?
  • nvm 有一个错字,我确实尝试过按照您写的操作,但仍然无法正常工作:c
  • Array 之前用new 试试(编辑答案以提供帮助)
  • 不,遗憾的是似乎无法正常工作抱歉,我将编辑我的问题以向您展示正在打印的内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-27
  • 2020-11-12
  • 1970-01-01
  • 1970-01-01
  • 2019-07-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多