繁体   English   中英

引入以下内容以避免未定义的 TypeError 在反应中导致一个奇怪的错误

[英]Introducing the folowing to avoid undefined TypeError in react causes a weird bug

我在 React 中工作,遇到了一个未定义的类型错误。 所以为了做到这一点,我做了以下,这是介绍|| {} || {}在返回语句中。 基本上它解决了它不再抛出类型错误的问题,但是,现在有一个错误,即使有数据,它也会呈现一个空的 state。 我认为数据只是加载缓慢。 有没有什么办法

filterCurrencyBalances() {
    const { amountByCurrency, amountByAsset, currentAccountId } = this.props;
    if (currentAccountId) {
      return amountByCurrency.find(acct => acct.id === currentAccountId || {}).assets;
    }
    return amountByAsset;
  }

错误消息说“无法读取未定义的属性(读取资产)”

有没有什么东西可以突出并导致错误?

您的{}在哪里没有意义。

return amountByCurrency.find(acct => acct.id === currentAccountId || {}).assets;

回调是:

acct => acct.id === currentAccountId || {}

因此,对于数组的第一个元素,要么acct.id === currentAccountId被满足,并且回调返回 true,要么它回退到{} ,并且对象是真实的,所以回调返回 - 并且第一个元素该数组是生成的“找到”项。

如果数组中不存在任何项目,则会引发错误,因为没有可迭代的内容。 回调中的空 object 除了破坏.find逻辑之外没有任何作用。

你应该改为做类似的事情

filterCurrencyBalances() {
    const { amountByCurrency, amountByAsset, currentAccountId } = this.props;
    if (currentAccountId) {
        const foundAcct = amountByCurrency.find(acct => acct.id === currentAccountId);
        return foundAcct ? foundAcct.assets : 0; // replace 0 with the desired default balance for no account
    }
    return amountByAsset;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM