无法调用子组件中可能“未定义”的对象

E.D*_*E.D 3 javascript undefined typescript react-native

在我的 expo typescript 应用程序中,我的根组件中有一个函数:

  const getCardType = (type = ECardType.WOOD) => {
    setCardType(type);
  };
Run Code Online (Sandbox Code Playgroud)

并将其传递到我的第一个子组件中:

  <Slider data={slideData} autoPlay={false} getCardType={getCardType} />
Run Code Online (Sandbox Code Playgroud)

这是我传递函数的第一个子组件,它类型声明:

  readonly getCardType?: (type: ECardType) => void;



  const Slider: React.FunctionComponent<ISliderProps> = ({
    data,
    autoPlay,
    getCardType,
 })
Run Code Online (Sandbox Code Playgroud)

之后我将其传递给第二个子组件:

<SliderCardItem cardItem={item} index={index} getCardType={getCardType} />
Run Code Online (Sandbox Code Playgroud)

在这个SliderItem组件中,我使用这个函数:

  useEffect(() => {
    getCardType(cardType);
  }, [cardType]);
Run Code Online (Sandbox Code Playgroud)

但出现 TS 错误: 无法调用子组件中可能“未定义”的对象

我在onPress()中设置了下面的cardType 我仅在此组件中出现此错误 有解决此错误的想法吗?

lia*_*gbs 7

getCardType可能是未定义的,如您的类型中所述:

getCardType?: (type: ECardType) => void;

然后你尝试调用它而不检查它是否存在:

useEffect(() => {
  getCardType(cardType);
}, [cardType]);
Run Code Online (Sandbox Code Playgroud)

因此,您需要执行该检查:

useEffect(() => {
  if (getCardType) getCardType(cardType);
}, [cardType]);
Run Code Online (Sandbox Code Playgroud)

或者使用可选的链接:

useEffect(() => {
  getCardType?.(cardType);
}, [cardType]);
Run Code Online (Sandbox Code Playgroud)

如果它始终存在,那么您可以在您的类型中将其设置为非可选:

getCardType: (type: ECardType) => void;