作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
代码给了我这个错误:
我看到错误
TypeError: TypeError: Cannot read property 'name' of undefined
....
constructor(props) {
super(props);
this.state = {
sts: [
{ code: '1', name: 'فعال' },
{ code: '2', name: 'غیر فعال' }
],
usedin: [
{ code: 'CASETYPE', name: 'نوع ظرف' },
{ code: 'CASEMAT', name: 'جنس' }
]
};
};
.....
enterAdd = () => {
//console.log("enterAdd");
this.setState({
openForm: true,
editItem: {
srl: Math.max.apply(Math, this.state.infodata.map(({ srl }) => srl)) + 1,
dsc: "",
sts: "1",
usedin: "CASETYPE",
uDateTime: "",
uauserSrl: 1
},
editMode: false,
})
}
<Column
field="usedin"
title="محل استفاده"
width="120px"
cell={(props) => (
<td>
<div>
{props.dataItem[props.field] ? this.state.usedin.find(
({ code }) => code === props.dataItem[props.field]).name : ""}
</div>
</td>
)}
/>
最佳答案
问题
看来this.state.usedin.find(({ code }) => code === props.dataItem[props.field])
有时无法找到匹配项并返回 undefined
.当您尝试访问 undefined object 的属性时会引发错误。
Array.prototype.find
The
find()
method returns the value of the first element in theprovided array that satisfies the provided testing function. If novalues satisfy the testing function,undefined
is returned.
array.prototype.find
时要优雅地处理函数在找不到匹配项时返回 undefined。
const usedin = props.dataItem[props.field] &&
this.state.usedin.find(({ code }) => code === props.dataItem[props.field]);
<td>
<div>
{usedin ? usedin.name : ""}
</div>
</td>
解决方案 2 - 首先搜索并使用
Optional Chaining和
Nullish Coalescing operator .
const usedin = props.dataItem[props.field] &&
this.state.usedin.find(({ code }) => code === props.dataItem[props.field]);
<td>
<div>
{usedin?.name || ""}
</div>
</td>
注:如果您有合理的保证
dataItem
可在
props
上获得object 那么你也可以跳过空检查。在这种情况下,您只需比较
code === undefined
这可能适合您的用例。
const usedin = this.state.usedin.find(
({ code }) => code === props.dataItem[props.field]
);
关于javascript - 类型错误 : Cannot read property 'name' of undefined [reactjs] with oracle database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66513901/
我是一名优秀的程序员,十分优秀!