[英]Cannot invoke an object which is possibly 'undefined' in children component
In my expo typescript app, I have a function in a root component:在我的 expo typescript 应用程序中,我在根组件中有一个函数:
const getCardType = (type = ECardType.WOOD) => {
setCardType(type);
};
and pass it in my first child component:并将其传递到我的第一个子组件中:
<Slider data={slideData} autoPlay={false} getCardType={getCardType} />
Here is my first child component where I pass the function, and it types declaration:这是我传递函数的第一个子组件,它类型声明:
readonly getCardType?: (type: ECardType) => void;
const Slider: React.FunctionComponent<ISliderProps> = ({
data,
autoPlay,
getCardType,
})
After that I pass it into a second child component:之后,我将它传递给第二个子组件:
<SliderCardItem cardItem={item} index={index} getCardType={getCardType} />
And in this SliderItem component, I use this function:在这个SliderItem组件中,我使用了这个函数:
useEffect(() => {
getCardType(cardType);
}, [cardType]);
But Have a TS error: Cannot invoke an object which is possibly 'undefined' in children component但是有一个 TS 错误:无法调用子组件中可能“未定义”的对象
I set the cardType below in an onPress()我在onPress() 中设置了下面的cardType
I have this error only in this component我只在这个组件中有这个错误
An idea to fix this error?解决此错误的想法?
Remove the ?
删除
?
in the type declaration, if it's required.在类型声明中,如果需要的话。 If it's not required, you have to check if it exists first.
如果不需要,则必须先检查它是否存在。
Another point, getCardType
is actually a dependency of that effect as well, but by looking at it it's safe, to ignore it (because it just wraps a setState) call.另一点,
getCardType
实际上也是该效果的依赖项,但通过查看它是安全的,忽略它(因为它只是包装了一个 setState)调用。
I don't like ignoring stuff, though.不过,我不喜欢忽略东西。 So if I were you, I'd probably write it like this:
所以如果我是你,我可能会这样写:
// useCallback makes getCardType referentially identical between renders
const getCardType = useCallback((type = ECardType.WOOD) => {
setCardType(type);
// safe to ignore setCardType in the dependencies because it's a dispatcher
},[]);
// ... and in the child:
useEffect(() => {
getCardType(cardType);
}, [ getCardType, cardType ]);
I'm honestly dying to know what that useEffect
is about in the child, because it smells a little fishy.老实说,我很想知道孩子
useEffect
是什么,因为它闻起来有点腥。
getCardType
might be undefined, as stated in your type here: getCardType
可能未定义,如您在此处的类型中所述:
getCardType?: (type: ECardType) => void;
Then you're trying to call it without checking if it exists:然后你试图在不检查它是否存在的情况下调用它:
useEffect(() => {
getCardType(cardType);
}, [cardType]);
So you'll need to perform that check:因此,您需要执行该检查:
useEffect(() => {
if (getCardType) getCardType(cardType);
}, [cardType]);
or with optional chaining:或使用可选链接:
useEffect(() => {
getCardType?.(cardType);
}, [cardType]);
If it will always be present then you can make it non optional in your type:如果它始终存在,那么您可以在您的类型中将其设为非可选:
getCardType: (type: ECardType) => void;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.