【问题标题】:Cannot invoke an object which is possibly 'undefined' in children component无法调用子组件中可能“未定义”的对象
【发布时间】:2021-10-15 12:32:13
【问题描述】:

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

  const getCardType = (type = ECardType.WOOD) => {
    setCardType(type);
  };

并将它传递给我的第一个子组件:

  <Slider data={slideData} autoPlay={false} getCardType={getCardType} />

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

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



  const Slider: React.FunctionComponent<ISliderProps> = ({
    data,
    autoPlay,
    getCardType,
 })

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

<SliderCardItem cardItem={item} index={index} getCardType={getCardType} />

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

  useEffect(() => {
    getCardType(cardType);
  }, [cardType]);

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

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

【问题讨论】:

  • 顺便说一句...一个名为getCardType 的函数在内部调用了一个名为setCardType 的函数,这听起来像是你在为以后混淆的错误做准备。它实际上不是获取一个值,而是设置一个值。

标签: javascript typescript react-native undefined


【解决方案1】:

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

getCardType?: (type: ECardType) =&gt; void;

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

useEffect(() => {
  getCardType(cardType);
}, [cardType]);

因此您需要执行该检查:

useEffect(() => {
  if (getCardType) getCardType(cardType);
}, [cardType]);

或使用可选链接:

useEffect(() => {
  getCardType?.(cardType);
}, [cardType]);

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

getCardType: (type: ECardType) =&gt; void;

【讨论】:

  • 感谢通过可选链接检查它是否存在,它可以工作;)
【解决方案2】:

如果需要,请删除类型声明中的 ?。如果不需要,则必须先检查它是否存在。

另外一点,getCardType 实际上也是该效果的依赖项,但是通过查看它是安全的,可以忽略它(因为它只是包装了一个 setState)调用。

不过,我不喜欢忽略一些东西。所以如果我是你,我可能会这样写:

  // 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 ]);

老实说,我很想知道useEffect 在孩子身上是什么意思,因为它闻起来有点腥。

【讨论】:

    猜你喜欢
    • 2020-10-02
    • 2021-12-21
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 2021-01-03
    • 2019-06-08
    相关资源
    最近更新 更多