gpt4 book ai didi

javascript - 类型错误 : Cannot read property 'name' of undefined [reactjs] with oracle database

转载 作者:行者123 更新时间:2023-12-04 08:00:08 28 4
gpt4 key购买 nike

代码给了我这个错误:
我看到错误

TypeError: TypeError: Cannot read property 'name' of undefined


当我运行项目时出现。
我找不到确切的问题在哪里
我发送了我认为与此错误最相关的代码的 3 个不同部分。
....
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。
解决方案 1 - 首先搜索,然后通过三元有条件地呈现。
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 ChainingNullish 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com