首页 > 解决方案 > REACT JS:如何在地图内向尚未启动的数组添加键?

问题描述

我已经尝试了几天来解决这段代码,并成功地慢慢地通过它,但我仍然很遗憾地卡住了这里的问题:

首先,我想要实现的是显示一个 X 数组,其中所有值都从 1 开始有人给了我一个提示,我尝试了一下,但它似乎不起作用,可能是因为我没有分配它的“钥匙”

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

如果我没记错的话,这应该会创建一个所有值都从 1 开始的数组。

但这就是打印的内容:

在此处输入图像描述

当我手动将 1 作为值至少分配给第一个值时,它看起来像这样:

在此处输入图像描述

但是由于我只是手动设置 const [cantidad, setCantidad] = useState([1]);它显然不会工作,因为它只是第一个值,这就是为什么我尝试以前的代码const [cantidad, setCantidad] = useState( new Array(libros.length).fill(1) ); 但遗憾的是没有工作(或者我只是错过了关键组件),因为这是它给我的错误(虽然我什至没有使用 li/list) 这里是它发送给我的地方基本上是一个列表/键信息,但似乎键相当于我在开始时给出的“索引”值列表和键

在此处输入图像描述

无论如何继续前进,这个想法是通过调用 2 个函数来增加数字的数量/候选者,如果您单击左侧的按钮,它会添加 + 1,如果是右侧的按钮,则非常简单,它会mas-1menos我认为正确涵盖:

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);
        }
      };

最后这就是我打印表格的方式

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

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

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

                     ))}
                </tbody>

这是控制台日志显示的内容: 在此处输入图像描述

我已经阅读了数组地图,并且我了解常规情况的基础知识没有看到我当前情况的类似示例任何帮助/提示都非常感谢,这是我的实际代码(整个代码):

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(cantidad)

    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((libros, index) => (
                        <tr >
                        <td>
                            <button onClick = {() => mas(index)}/>
                            {cantidad[index]}
                            {console.log(cantidad)}
                            {console.log([index])}
                            <button onClick = {() => menos(index)}/>
                        </td>
                        <td>{libros.grado}</td>

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

                        <td >{libros.editorial}</td>
                        <td >${parseFloat(libros.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

我知道我最近做了很多问题 buuuut 我想尽我所能学习和练习,哦,我也在使用 Firebase 作为我的数据库唯一不是来自数据库的值是 cantidad/amount 所有其他 grado/课程描述/描述等来自数据库,这就是为什么我没有遇到这些问题。

标签: javascriptreactjsfirebasegoogle-cloud-firestorearray-map

解决方案


您的问题有点不清楚,但我在您的代码中发现了以下问题。

cantidad您正在使用另一个状态将默认值设置为状态libros,但它只会在您的组件第一次呈现时设置一次。所以你应该useEffect在这里使用钩子来更新cantidad每当libros更改。

useEffect(()=>{
  setCantidad(new Array(libros.length).fill(1))
}, [libros])

在循环某个数组和渲染组件列表时始终使用键。

{libros.map((libros, index) => (
    <tr key={libros.id || index}>
      ...
    </tr>
)}

推荐阅读