英文:
JavaScript Nested Object Deconstruction "Cannot read properties of null" with default value
问题
我正在尝试在JavaScript中解构一个对象。我已经在解构中分配了默认值,但仍然出现以下错误:
React Router 在渲染过程中捕获到以下错误 TypeError: Cannot read properties of null (reading 'responseTimePoints')
这是我的解构代码:
const testRun = useTestRunModel();
const {
id: testRunId,
graphData: { responseTimePoints = [] } = {},
} = testRun || {};
实际上,我希望在testRun
/ testrun.graphData
/ testRun.graphData.responseTimePoints
为null或未定义的情况下,将responseTimePoints
设置为一个空数组。
我不确定是否重要,但我正在使用React 18.2与TypeScript 5.1.6,这是我的tsconfig.json配置:
"compilerOptions": {
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"module": "esnext",
"target": "es2015",
"allowJs": false,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"isolatedModules": true,
"jsx": "react-jsx",
"moduleResolution": "node",
"noEmit": true,
"noFallthroughCasesInSwitch": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"baseUrl": "./",
"rootDir": "./",
"types": []
}
英文:
I'm trying to deconstruct an object in JavaScript. I've assigned default values in the deconstruction but I'm still getting the following error:
React Router caught the following error during render TypeError: Cannot read properties of null (reading 'responseTimePoints')
This is my deconstruction code:
const testRun = useTestRunModel();
const {
id: testRunId,
graphData: { responseTimePoints = [] } = {},
} = testRun || {};
This is the output of the testRun
object:
Essentially, I'd like responseTimePoints
to be set to an empty array in the event that testRun
/ testrun.graphData
/ testRun.graphData.responseTimePoints
are null or undefined.
I'm not sure if it matters, but I am using React 18.2 with TypeScript 5.1.6, and this is my tsconfig.json:
"compilerOptions": {
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"module": "esnext",
"target": "es2015",
"allowJs": false,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"isolatedModules": true,
"jsx": "react-jsx",
"moduleResolution": "node",
"noEmit": true,
"noFallthroughCasesInSwitch": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"baseUrl": "./",
"rootDir": "./",
"types": []
}
答案1
得分: 1
默认初始化器在解构(和函数参数)中仅在值为undefined
(或属性/参数完全不存在)时才生效,而在值为null
时不生效。
请改用nullish coalescing:
const testRun = useTestRunModel();
const testRunId = testRun?.id;
const responseTimePoints = testRun?.graphData?.responseTimePoints ?? [];
英文:
Default initialisers in destructuring (and function parameters) only apply when the value is undefined
(or the property/argument is absent altogether), not when it is null
Use nullish coalescing instead:
const testRun = useTestRunModel();
const testRunId = testRun?.id;
const responseTimePoints = testRun?.graphData?.responseTimePoints ?? [];
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论