0

零件:

  const { transactions } = useContext(GlobalContext);

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

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

由于 toFixed,总 const 引发错误

如果没有 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>
  );
};
4

2 回答 2

0

因为金额是字符串,将其更改为数字,它将起作用。

amounts.reduce((acc, item) => (Number(acc) + Number(item)), 0).toFixed(2);
于 2021-07-19T06:21:08.157 回答
0

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

在 JS 中:
Number + Number = Number
但是即使 + 运算符的任一侧是String并且另一侧是 aNumber那么结果将是 a String

String + Number = String
Number + String = String

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

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

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

其余的将是相同的。

于 2021-07-20T07:54:28.213 回答