[英]How to fix error cannot read property of undefined using react and typescript?
i get error cannot read property of undefined using react and typescript?我得到错误无法使用反应和 typescript 读取未定义的属性?
what i am trying to do?我想做什么?
i have a parentComponent within which i make a query to get some data "itemData".我有一个 parentComponent,我在其中进行查询以获取一些数据“itemData”。 and pass this itemData to the ChildComponent.
并将此 itemData 传递给 ChildComponent。
in the childComponent i am getting one property from itemData that is availableItems and passing it to Select menu options.在 childComponent 中,我从 itemData 获取一个可用的属性,并将其传递给 Select 菜单选项。
below is the code,下面是代码,
const ParentComponent = () => {
const itemData = useItemDataQuery();
return (
<ChildComponent itemData={itemData.data}/>
);
}
const ChildComponent =(itemData: any) => {
const options = react.useMemo(() => { //error here
const output = itemData && itemData[0].availableItems;
return output;
}
}, [itemData]);
return (
<SelectMenu options ={options} value="hello"/>
);
} }
itemData is an array of object like below itemData 是一个 object 数组,如下所示
const itemData = [
{
name: 'name1',
availableItems: [
'Item1',
'Item2',
],
}
]
i am accessing availableItems with itemData && itemData[0].availableItems but still giving an error.我正在使用 itemData && itemData[0].availableItems 访问 availableItems 但仍然给出错误。
Could someone help me fix this.有人可以帮我解决这个问题。 thanks.
谢谢。
EDIT:编辑:
I have tried like below我试过如下
const options = react.useMemo(() => {
if (itemData && itemData.length > 0) {
const output = itemData[0].availableItems;
return output;
}
}
}, [itemData]);
this works. but under SelectMenuComponent the prop options shows error "no overload matches this call. Type Maybe<string>[]|undefined|null is not assignable to type .
return (
<SelectMenu options ={options} value="hello"/> //error here
);
could someone help me with this.有人可以帮我解决这个问题。 thanks.
谢谢。
react
seems to be undefined. react
似乎是未定义的。
Just add this statement at top of your imports:只需在导入顶部添加此语句:
import React from "react";
and use React.useMemo
并使用
React.useMemo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.