我在 React 中作業,遇到了一個未定義的型別錯誤。所以為了做到這一點,我做了以下事情,這是|| {}在 return 陳述句中引入的。基本上它解決了它不再拋出型別錯誤的問題,但是,現在有一個錯誤,它呈現一個空狀態,即使有資料。我認為資料只是加載緩慢。有沒有什么辦法
filterCurrencyBalances() {
const { amountByCurrency, amountByAsset, currentAccountId } = this.props;
if (currentAccountId) {
return amountByCurrency.find(acct => acct.id === currentAccountId || {}).assets;
}
return amountByAsset;
}
錯誤訊息說“無法讀取未定義的屬性(讀取資產)”
有沒有什么東西可以突出并導致錯誤?
uj5u.com熱心網友回復:
你{}在哪里沒有意義。
return amountByCurrency.find(acct => acct.id === currentAccountId || {}).assets;
回呼是:
acct => acct.id === currentAccountId || {}
因此,對于陣列的第一個元素,要么acct.id === currentAccountId滿足,回呼回傳 true,要么回退到{},并且物件是真實的,所以回呼回傳 - 陣列的第一個元素是結果“找到”項.
如果陣列中不存在任何專案,則會引發錯誤,因為沒有可迭代的內容。.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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/418404.html
標籤:
