javascript - REACT JS - 如何在 map 内进行求和?

标签 javascript arrays reactjs function array-map

最初我想问如何在 map 内调用函数,但我意识到我调用函数的方式没有做任何错误,所以我只是认为我的代码是错误的。

所以我试图对我正在渲染的 map 的所有价格进行求和,有时这些价格会因为人们可能想要的数量而变化,所以我打电话:

//My function call inside the map
{calculateTotal(fixedPrice)}

//The function
const calculateTotal = (price) => {
        setTotalPrice (totalPrice + price)
      }

但是我得到了这个错误返回

enter image description here

我不明白为什么将 2 个数字相加一定次数(在本例中为 9)会导致无限循环。我想做的就是将所有价格汇总到一个变量中,如果候选者/数量发生变化,它也会添加这些变化。

enter image description here

完整代码,以防您需要

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

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

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

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

    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]++);
        setCantidad([...cantidad])
      };

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

      const calculateTotal = (price) => {
        setTotalPrice (totalPrice + price)
      }

    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, fixedPrice) => (
                        <tr key={libros.id || index}>
                        <td>
                            <button onClick = {() => mas(index)}/>
                            {cantidad[index]}
                            {console.log(cantidad)}
                            <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 >${fixedPrice = parseFloat(libros.precio).toFixed(2) * cantidad[index]}</td>
                        
                        {calculateTotal(fixedPrice)}
                        </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

最佳答案

这涉及两个理论点。

  1. 您必须注意到 map 返回一个值数组。因此,如果您调用一个函数,它将被调用多次。

  2. 在 React 中,当状态发生变化时,组件将在每次变化时重新渲染。在map中,您调用一个改变状态的函数。然后状态改变重新渲染所有组件。 map 一次又一次地调用该函数。这是一个无限循环。

如果您想计算总价,必须在 map 返回之外进行。

独立的逻辑。在组件返回之外进行所有计数。然后在组件返回中只显示 jsx 元素

关于javascript - REACT JS - 如何在 map 内进行求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69247026/

相关文章:

javascript - 按 Asc 和 Desc 日期排序

javascript - Jestjs 与 Expo-cli。不变违规 : Element type is invalid

javascript - 停止嵌入式 youtube iframe?

javascript - 如何将单击的 div 的类名作为参数传递给函数

javascript - 如何使用 clojurescript 或 om-next 在 dom 元素上切换类

javascript -\t 在 JavaScript 中不起作用

arrays - 可变的用户选择

javascript - 函数中的递归调用如何工作?

java - ArrayIndexOutOfBoundsException : don't understand why

reactjs - Gatsby - 无法读取 null 的属性 'childImageSharp'