无法调用可能未定义的对象

Dim*_*fst 0 javascript typescript reactjs

我正在使用带有反应的打字稿,但出现此错误。

Cannot invoke an object which is possibly 'undefined'.ts(2722)
const onChange: ((...args: any[]) => any) | undefined
Run Code Online (Sandbox Code Playgroud)

这是我收到错误的代码。

interface FilterGroupsProps {
  data?: any[];
  selectedGroups?: any[];
  onChange?: (...args: any[]) => any;
}

// Inside the class
  onClick = (groupName: string) => (event: MouseEvent<HTMLButtonElement>) => {
    const { onChange } = this.props;
    event.preventDefault();
    onChange(groupName);
  };

//Inside the render:
          {allUniqueGroups.map((group: string) => (
            <a
              key={group}
              className="dropdown-item d-flex justify-content-between align-items-center"
              href="#"
              onClick={this.onClick(group)}
            >
Run Code Online (Sandbox Code Playgroud)

我对此错误的不理解如下:呈现此 onClick 时,groupName 应该可用。

这意味着我有点困惑我的安全案例应该在哪里处理。你能在这里解释一下这个问题吗?以及为我提供解决此问题的方法。

Mar*_*vic 8

看看FilterGroupsProps

interface FilterGroupsProps {
  data?: any[];
  selectedGroups?: any[];
  onChange?: (...args: any[]) => any;
}
Run Code Online (Sandbox Code Playgroud)

onChange可能是undefinedprovided

这是我的方法:

onClick = (groupName: string) => (event: MouseEvent<HTMLButtonElement>) => {
  if (this.props.onChange) {
   const { onChange } = this.props;
   event.preventDefault();
   onChange(groupName);
  }
  // or do something else...
};
Run Code Online (Sandbox Code Playgroud)

或者从评论的解决方案兰迪删除optional 标志onChange方法:

interface FilterGroupsProps {
  data?: any[];
  selectedGroups?: any[];
  onChange: (...args: any[]) => any;
}
Run Code Online (Sandbox Code Playgroud)