javascript - 使用可选链接接收 TypeError:无法读取未定义的属性“数据”
问题描述
我收到错误:
instrument.js:110 TypeError: Cannot read property 'data' of undefined
at useScenariosGraphql.tsx:128
at _o (react-dom.production.min.js:231)
at Du (react-dom.production.min.js:278)
at t.unstable_runWithPriority (scheduler.production.min.js:19)
at ql (react-dom.production.min.js:130)
at Fu (react-dom.production.min.js:277)
at react-dom.production.min.js:277
at A (scheduler.production.min.js:17)
at MessagePort.x.port1.onmessage (scheduler.production.min.js:14)
这发生在这里:
useEffect(() => {
let message: string | undefined;
const error = createError ?? updateError;
if (error) {
if (
// @ts-ignore
error.graphQLErrors?.[0].data?.messages?.[0] // <---- ERROR HERE Line 128
)
// @ts-ignore
message = error.graphQLErrors?.[0].data?.messages?.[0];
if (error?.message.includes('same organization as the scenario'))
message =
'To create a new scenario, all target areas must be in the same organization as that scenario. You can fix this in the data tab at the top.';
// @ts-ignore
if (typeof error?.graphQLErrors?.[0].data?.errors?.[1]?.data?.messages?.[0] === 'string')
// @ts-ignore
message = error?.graphQLErrors?.[0].data?.errors?.[1]?.data?.messages?.[0];
if (!message) {
message = `Something went wrong with the network request`;
console.log(error.message);
}
addToast(message, 10000);
}
}, [addToast, createError, updateError]);
@ts-ignore
是因为 GraphQL 错误类型没有数据属性,但返回的对象有时会从 GraphQL 后端。
无论哪种方式,如果它存在或不存在,为什么data
我在使用可选链接时无法读取 undefined ?当它没有找到数组0
的索引时,它不应该解析为 undefined吗?graphQLErrors
我们知道变量error
存在是因为 if 语句。所以现在我正在检查error.graphQLErrors[0]
哪个是undefined
......但这就是我使用可选链接而不是冗长的原因:
if (
error.graphQLErrors[0] &&
error.graphQLErrors[0].data &&
error.graphQLErrors[0].data.messages[0]
)
但它没有按预期工作......请帮助。
编辑
好的,我看到我也需要?
在索引之后。第一个问号是说索引是否真的存在,第二个问号是否该索引处的值不是空值variable?.[0]?
解决方案
?
访问graphQLErrors
数组时缺少可选的链接运算符:
error.graphQLErrors?.[0].data?.messages?.[0]
改成:
error.graphQLErrors?.[0]?.data?.messages?.[0]
推荐阅读
- c# - 为什么我只降低图像质量时图像被旋转?
- python - 当 pandas 数据框不包含列标签时切片一组列
- angular5 - 使用角度为 5 或 6 的 PouchDB
- python - 如果存在 YYYY,则 Python 保留行,否则删除该行
- python - Python-具有条件的函数中的Numpy数组
- javascript - Flexbox 下拉子菜单
- c# - 为什么 typeof(Child<>).BaseType.IsGenericTypeDefinition 为假?
- android - Android - Espresso - 当列表中存在其他对象时断言对象
- java - Java不同的引用类型和类对象
- php - phpMailer IMAP 编码/解码