首页 > 解决方案 > 当反应中没有虚拟帐户时,如何添加条件来覆盖此未定义的值

问题描述

当数据中没有包含类型属性的帐户时,我收到“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;
  }

标签: javascriptreactjsnullundefinedtypeerror

解决方案


您可以使用可选链接:

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;

推荐阅读