数组缩减器正在连接。不加总和。上下文反应

array reducer is concatenating. not adding to sum. context with react

组件:

  const { transactions } = useContext(GlobalContext);

  const amounts = transactions.map((transaction) => transaction.amount);

  const total = amounts.reduce((acc, item) => (acc += item), 0).toFixed(2);

总常量抛出错误,因为 toFixed

没有 toFixed,我的数字会连接成字符串。

我的数字如何被视为字符串???????

我已经尝试使用 Number 和 parseInt 将字符串转换为数字。它没有用。

为什么数字连接成字符串?

这是全局状态:

import React, { createContext, useReducer } from "react";
import AppReducer from "./AppReducer";

//Initial State
const initialState = {
  transactions: [
    {
      id: 1,
      name: "Payment to Molly Sanders",
      href: "#",
      category: "expense",
      amount: "200",
      currency: "USD",
      status: "success",
      date: "July 11, 2020",
      datetime: "2020-07-11",
    },
    {
      id: 2,
      name: "Rent",
      href: "#",
      category: "expense",
      amount: "100",
      currency: "USD",
      status: "processing",
      date: "July 1, 2020",
      datetime: "2020-07-11",
    },
    {
      id: 3,
      name: "Google",
      href: "#",
      category: "income",
      amount: "500",
      currency: "USD",
      status: "success",
      date: "July 18, 2020",
      datetime: "2020-07-18",
    },
  ],
};

//Create context
export const GlobalContext = createContext(initialState);

//Provider component
export const GlobalProvider = ({ children }) => {
  const [state, dispatch] = useReducer(AppReducer, initialState);

  return (
    <GlobalContext.Provider
      value={{
        transactions: state.transactions,
      }}>
      {children}
    </GlobalContext.Provider>
  );
};

因为amount是字符串,改成数字就可以了。

amounts.reduce((acc, item) => (Number(acc) + Number(item)), 0).toFixed(2);

您在 initialState 中将 amount 类型作为字符串,这就是它连接的原因。

在 JS 中:
Number + Number = Number
但即使 + 运算符的两边是 String 而另一边是 Number 那么结果将是 String:

String + Number = String
Number + String = String

所有金额最好使用您initialState中的数字。例如
amount: 500 而不是 amount: "500"

或者,如果您出于某些原因将其放入,则在第二步中使用类型转换使其看起来更简洁:

 const amounts = transactions.map((transaction) => Number(transaction.amount));

其他同理