4 回答

TA貢獻1812條經驗 獲得超5個贊
如果你看到下面的代碼,如果它沒有找到與給定的 witnessId 匹配的任何 account_id,則 witness var 可以是未定義的。在這種情況下,會拋出錯誤,所以這樣做
getWitnessName = (witnessId) => {
if (this.props.witnesses) {
const witness = this.props.witnesses.find(el => el.account_id === witnessId)
return witness ? witness.account_name : `No witness for given id: ${witnessId}`;
}
}

TA貢獻1111條經驗 獲得超0個贊
您可以使用可選鏈接
添加一個nullish 合并運算符來完成圖片而不是正常的,||
它不會對虛假值做出反應
return this.props.witnesses.find(el => el.account_id === witnessId)?.account_name ?? "N/A";
它將處理丟失的 witness 和丟失的 account_name
例子
const props = {
witnesses: [
{ account_id: 1, account_name: "Fred"},
{ account_id: 2, account_name: "Joe" },
{ account_id: 3 }]
};
const getName = witnessId => props.witnesses
.find(el => el.account_id === witnessId)?.account_name ?? "N/A";
console.log(getName(1))
console.log(getName(2))
console.log(getName(3))
console.log(getName(4))

TA貢獻1830條經驗 獲得超9個贊
嘗試首先驗證以獲取屬性,這是因為它沒有找到任何驗證輸入。然后 find 返回 undefined,你不能從 undefined 中獲取屬性。
例如
this.props.witnesses.find(el => el.account_id === witnessId)?.account_name ?? 'Account Not Found';

TA貢獻1848條經驗 獲得超10個贊
getWitnessName = (witnessId) => {
if (this.props.witnesses) {
let foundWitnesses = this.props.witnesses.find(el => el.account_id === witnessId);
if(foundWitnesses)
return foundWitnesses.account_name;
else
return 'Not found';
}
}
添加回答
舉報