【问题标题】:Property 'then' does not exist on type 'IPayload<T>'类型“IPayload<T>”上不存在属性“then”
【发布时间】:2020-03-29 18:40:09
【问题描述】:

我有一个使用 JHipster 6.x 和 React JS 作为 UI 生成的应用程序。在许多屏幕中,我使用诸如

之类的 redux 方法获取数据

方法:

export const getStudentsByCriteria: ICrudSearchAction<IStudent> = (query, page, size, sort) => ({
  type: ACTION_TYPES.SEARCH_STUDENTS,
  payload: axios.get<IStudent>(`${apiUrl}?${query}${sort ? `&page=${page}&size=${size}&sort=${sort}` : ''}`)
});

呼叫:

(this.props.getStudentsByCriteria('classSectionId.equals=' + classSectionId, 0, 50, "firstName,asc") as IPayload<IStudent>).payload.then((response) => { ... }

它一直工作得很好,但突然间我开始收到错误:TS2339: 类型 'IPayload | 上不存在属性'then' ((调度:任何)=> IPayload)'。 类型“IPayload”上不存在属性“then”

简单地调用 .then 会在 MS Code 中产生编译错误,但在本地运行没有任何问题,但是由于编译错误而不允许构建战争

(this.props.getStudentsByCriteria('classSectionId.equals=' + classSectionId, 0, 50, "firstName,asc").then((response) => { ... }

这应该返回 IPayload 并且 IPayload.payload.then ... 必须工作。它一直在工作,它突然停止工作很奇怪。

【问题讨论】:

  • 也许你之前有一个await
  • 我没有。我没有更改代码中的任何内容。是的,项目中添加了一些组件

标签: reactjs promise jhipster


【解决方案1】:

我通过将返回的对象转换为 Promise 使其工作,如下面的代码所示:

(this.props.getStudentsByCriteria('classSectionId.equals=' + classSectionId, 0, 50, "rollNo,firstName") as unknown as Promise<IStudent[]>).then((response) => {
      this.setState({
        sectionStudents: (response as any).value.data
      });
    });

不得不使用 ... 和 Promise 一样不为人知。 VS Code 将响应类型显示为 IStudent[] 但是当我尝试调用 map 函数时它会在运行时出错。 (IStudent[] 不支持地图)。由于编译时的响应类型是 IStudent[],它没有 value 属性并给出错误,因此必须将其转换为“any”才能获取 value.data。调试代码解决了这个问题。

为什么这段代码停止返回 IPayload 对我来说仍然是个谜。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 2020-11-07
    • 1970-01-01
    • 2021-05-31
    • 2020-01-11
    • 2020-12-27
    相关资源
    最近更新 更多