为什么这个辅助函数会返回subtotal
和tax
的值,但是对于fees
和ordertotal
却返回NAN
?
OrderSummary.jsx
const taxRate = 0.0925;
const OrderSummary = ({ addCSS, classes, merchantId, merchantName, step, setStep }) => {
const context = useContext(ProductContext);
let items = Array.isArray(context.cart) ? context.cart : [];
if (step === 4) {
items = Array.isArray(context.order) ? context.order : [];
}
const subtotal = items.reduce((acc, cur) => {
return acc + cur.total * (cur.company_id === merchantId) * 1;
}, 0);
let tax = subtotal * taxRate;
tax = parseFloat(tax.toFixed(2));
let fee = subtotal * ApplicationFee * 0.01;
fee = parseFloat(fee.toFixed(2));
const total = subtotal + tax + fee;
<LineItem>
<S2>Subtotal</S2>
<S2>{formatCurrency(subtotal)}</S2>
</LineItem>
<LineItem>
<S2>Tax</S2>
<S2>{formatCurrency(tax)}</S2>
</LineItem>
<LineItem>
<S2>Fee</S2>
<S2>{formatCurrency(fee)}</S2>
</LineItem>
<Total>
<H5>Order Total</H5>
<H5>{formatCurrency(total)}</H5>
</Total>
helperFunctions.jsx
export const formatCurrency = (num) => {
if (typeof num !== 'number') return num
return new Intl.NumberFormat('en-US', {style: 'currency', currency: 'USD'}).format(num)
}
addTotals = () => {
let subTotal = 0;
this.state.cart.map((item) => (subTotal += item.total));
const tempFees = subTotal * ApplicationFee * 0.01;
const fees = parseFloat(tempFees.toFixed(2));
const total = subTotal + fees;
this.setState(() => {
return {
cartSubTotal: subTotal,
cartFees: fees,
cartTotal: total,
};
});
};
NaN
,format
将返回"NaN"
。 - Heretic MonkeysubTotal
显示正常,它似乎是唯一可能出现问题的地方。 - raina77owsubTotal
显示正常(这意味着它是一个合适的值),但fee
不正常,并且唯一参与计算后者 (subtotal * ApplicationFee * 0.01
) 的动态值是 ApplicationFee,则问题在于 ApplicationFee。检查该值:可以通过记录日志或在代码中设置断点来进行检查。 - raina77ow