反应如何从地图函数中求和数字?

React how to sum numbers from a map function?

我如何从地图函数中求和数字? 我以数字形式获取每个月的所有价格。 我只得到单个数字,而不是来自我的映射函数的数组,所以我不能使用 reduce 函数

编辑:现在发布所有代码我希望它现在有助于更好地理解它。 这是我展示 carttotal 时得到的。 它显示了正确的月份,但不是总和 [当前输出][1]

const PayFees = () => {
  const [history, setHistory] = useState([]);
  const token = useSelector((state) => state.token);
  useEffect(() => {
    const getHistory = async () => {
      const res = await axios.get('/api/payment', {
        headers: { Authorization: token },
      });
      setHistory(res.data);
    };
    getHistory();
  }, [token, setHistory]);

  const sum = history
    .map((order) => order.carttotal)
    .reduce((prev, curr) => prev + curr, 0);

  const getYears = new Set(
    history.map((date) => {
      const year = dayjs(date.createdAt).format('YYYY');
      return year;
    })
  );
  const getMonths = new Set(
    history.map((date) => {
      const monthYear = dayjs(date.createdAt).format('MM/YYYY');
      return monthYear;
    })
  );

  const yearsArr = [...getYears];
  const monthArr = [...getMonths];
  return (
    <div>
      <div>
        {yearsArr.map((year) => {
          return (
            <div>
              <div>{year}</div>
              <div>
                {monthArr.map((month) => {
                  return dayjs(month, 'MM/YYYY').format('YYYY') === year ? (
                    <div>
                      {month}
                      {history.map((order) => {
                        console.log(order);
                        return dayjs(order.createdAt).format('MM/YYYY') ===
                          month ? (
                          <div>{order.carttotal}</div>
                        ) : (
                          ''
                        );
                      })}
                    </div>
                  ) : (
                    ''
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default PayFees;
```


  [1]: https://i.stack.imgur.com/Qvb5A.png

我相信还有其他方法,但你可以试试这个:

const [total, setTotal] = useState(0)

{history.map((order) => {
setTotal(total + order.carttotal)}}

然后在需要的地方调用{total}。

也许这是一个丑陋的解决方案,而且方法很长,但我很高兴我终于找到了解决方案。我创建了一个新组件,下面的代码一切正常

{yearsArr.map((year) => {
          return (
            <div>
              <div>{year}</div>
              <div>
                {monthArr.map((month) => {
                  return dayjs(month, 'MM/YYYY').format('YYYY') === year ? (
                    <>
                      {month}
                      <MonthlyFee date={month} />
                    </>
                  ) : (
                    ''
                  );
                })}
              </div>
            </div>
          );
        })}

月费部分:

const MonthlyFee = ({ date }) => {
  const [history, setHistory] = useState([]);
  const token = useSelector((state) => state.token);
  useEffect(() => {
    const getHistory = async () => {
      const res = await axios.get('/api/payment');
      setHistory(res.data);
    };
    getHistory();
  }, [token, setHistory]);

  const getMonthlyOrder = history.map((order) => {
    const monthlyOrder =
      date === dayjs(order.createdAt).format('MM/YYYY')
        ? order
        : { carttotal: 0 };
    return monthlyOrder;
  });

  const final = getMonthlyOrder
    .map((order) => order.carttotal)
    .reduce((prev, curr) => prev + curr, 0);

  return <div>{final}</div>;
};

export default MonthlyFee;