【问题标题】:React Native - make dummy db get real data from apiReact Native - 让虚拟数据库从 api 获取真实数据
【发布时间】:2020-08-13 09:59:51
【问题描述】:

我对 React Native 和 JS 很陌生,最近购买了一个带有 Dummy DB 的 React Native 模板。

理想情况下,我希望它从外部 JSON (api) 中提取数据,该 JSON (api) 是从我们已经运行的 PHP 网站生成的。

这是虚拟数据文件:

import {
  DoctorModel,
  TreatmentModel,
  CampaignModel,
  EventModel
} from "../models";

export const doctorsList: DoctorModel[] = [ { ##JSON HERE## } ];

export const treatmentsList: TreatmentModel[] = [ { ##JSON HERE## } ];

export const campaignList: CampaignModel[] = [ { ##JSON HERE## } ];

export const eventList: EventModel[] = [ { ##JSON HERE## } ];

我希望它导出为与上述相同的值,以便与当前应用配置无缝协作。

我已经尝试了以下...

export const doctorsList: DoctorModel[] = () =>
  fetch(' ##LINK TO API## ')
    .then((response) => response.json());

但是得到了这个错误:

Type '() => Promise<any>' is missing the following properties from type 'DoctorModel[]': pop, push, concat, join, and 27 more.

我已经在这里和其他平台寻找解决方案,但找不到任何东西。

再一次,如果我手动输入 JSON,如第一个代码 sn-p 所示,理想的结果将是它的工作方式。

非常感谢任何帮助,我仍在尝试围绕 React 解决问题! :)

【问题讨论】:

    标签: json typescript api react-native fetch


    【解决方案1】:

    这看起来不像是反应问题,而是打字稿问题。 Typescript 从您的返回值进行类型推断,以检查它是否与您所说的相符。

    简而言之:你刚刚声明了你的类型错误。

    函数不返回DoctorModel[],而是返回Promise&lt;DoctorModel[]&gt;

    export const doctorsList: Promise<DoctorModel[]> = () =>
      fetch(' ##LINK TO API## ')
        .then((response) => response.json() as DoctorsModel[]);
    
    

    所以改变那行应该会让你的打字稿编译器再次选择!

    【讨论】:

    • Type '() => Promise' 缺少来自类型 'Promise' 的以下属性:then、catch、[Symbol.toStringTag]、finally
    • Type 'Promise' 不是数组类型。
    • 嗨!非常感谢您的帮助,但它仍然显示:Type '() => Promise' is missing the following properties from type 'Promise': then, catch, [Symbol.toStringTag] ,终于
    猜你喜欢
    • 1970-01-01
    • 2017-01-31
    • 2021-09-26
    • 2021-12-23
    • 1970-01-01
    • 2023-03-11
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多