javascript - 当反应中没有虚拟帐户时,如何添加条件来覆盖此未定义的值
问题描述
当数据中没有包含类型属性的帐户时,我收到“TypeError:无法读取未定义的属性'类型'”。有什么方法可以绕过或推迟这个,直到提供一个虚拟帐户?我一直在寻找答案。我也尝试了 try catch 块。我提供了正在传递到文件中的帐户道具的图像。
static getDerivedStateFromProps(props, state) {
const { currentAccountId, accounts } = props;
const currentAccountType = currentAccountId ? accounts.filter(acc => acc.id === currentAccountId)[0].type : null;
const { currentTab } = state;
if (currentAccountType === ACCOUNT_TYPES.MANUAL && (currentTab === ACTIVITY_TABS.OPEN_ORDERS || currentTab === ACTIVITY_TABS.ORDER_HISTORY)) {
return {
...state,
currentTab: ACTIVITY_TABS.BALANCES,
transactionsDialogOpen: false,
};
}
return state;
}
解决方案
您可以使用可选链接:
const currentAccountType = currentAccountId ? accounts.filter(acc => acc.id === currentAccountId)[0]?.type : null;
但那是只在较新版本的节点中支持的东西,所以也许只是在 2 行上做呢?
const currentAccount = accounts.find((acc) => acc.id === currentAccountId);
const currentAccountType = currentAccount ? currentAccount.type : null;
推荐阅读
- java - 动态访问用户提供的类的用户提供的属性的有效/最佳方法是什么?
- javascript - 如果单击多个复选框中的一个复选框,如何触发功能
- php - 更改 laravel 缓存项的过期时间
- angular - 如何在 Angular 中使用 FormGroup 和对象数组
- matlab - 求解包含卡方概率的方程
- powershell-4.0 - 路径中的Powershell Get-ChildItem通配符?
- dialogflow-es - 没有为平台定义响应:webhookclient.send_ 上的 google_telephony
- riot.js - Riotjs - 前端页面结构
- python - 如何向 pandas df 添加一个新列,该列从另一个数据帧返回同一组中更大的最小值
- r - 将 NA 替换为 "No_"colname"_found"