删除一个组件中的项目会导致应用程序中断并抛出未定义的错误

Deleting item in one component causes app to break and throw undefined error

我正在使用 React 并使用 redux 来删除项目。该项目删除,但是,在删除项目后,应用程序立即崩溃并给出未定义的错误。它发生在与我正在尝试做的事情无关的组件中。

我的猜测是,当我删除一个项目时,使用该项目的其他组件将变得不确定,因为它不再从该元素填充 data/info。我不确定如何处理这个问题,因为我尝试了几个选项,包括我在研究过程中发现的以下选项,其中添加了“?”就在'.type'之前,但应用程序在这样做之后崩溃,说出错误的语法(意外符号):

const { currentAccountId, accounts } = props;
const currentAccountType = currentAccountId ? accounts.filter(acc => acc.id === currentAccountId)[0]?.type : null;

如果还有其他方法可以克服类型错误,请告诉我。谢谢!

你可以这样试试

const { currentAccountId, accounts } = props;
const currentAccountType = null;
if(currentAccountId) {
 let currentAccount = accounts.filter(acc => acc.id === currentAccountId)[0];
 if(currentAccount) currentAccountType = currentAccount.type;
}