当反应中没有虚拟帐户时,如何添加条件来覆盖此未定义的值

How can I add a conditional to override this undefined value when there is no dummy account in react

当数据中没有包含类型属性的帐户时,我收到“类型错误:无法读取未定义的 属性 'type'”。有什么方法可以绕过或推迟直到提供虚拟帐户为止?我一直在寻找答案。我也尝试了 try catch 块。我提供了传递到文件中的帐户道具的图像。

enter image description here

  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;