提问者:小点点

TypeError:Debts.map不是仅在chrome React上的函数


所以我有这个代码

export const Balance = () =>{
const {debts} = useContext(GlobalContext);

const amounts = debts.map(debt => debt.amount);
const total = amounts.reduce((acc, item) => (acc += item), 0).toFixed(2);
return (
        <div className="balance-container">
            <div>
            <h4>סכום כולל</h4>
            <h2><CountUp start={0} end={Number(total)} duration={2.5} separator=","></CountUp>&#8362;</h2>
            </div>
        </div>
    )

我得到的错误是:typeerror:debts.map不是一个函数

应用程序是崩溃的。 奇怪的是,当我将url(我的本地主机和端口)复制到firefox,或者移动中的chrome时,应用程序运行良好。。。

会有什么问题呢?


共1个答案

匿名用户

这很可能是因为debits为空或未定义。 一个惯用解决方案是在初始化时将该值默认为一个空数组:

const debts = []

而不是(你现在可能正在做的)

const debts = null

当你在一个空数组上调用。map时,它将不起作用,所以如果值还没有添加,它将得到很好的处理。 当用值填充债务数组时,将呈现这些值。