【问题标题】:Trying to return a promise for React-Select dropdown试图为 React-Select 下拉菜单返回一个承诺
【发布时间】:2022-09-30 03:45:33
【问题描述】:

我这里有一个类型:

type Person = {
  value: string;
  label: string;
};

我在这里有一个代码块作为承诺,它从 API 获取数据 - 然后它将它转换为反应组件的正确类型的数组,然后我希望在承诺中使用 return 命令返回它 - 就像这样:

const fetchDropDown = async () : Promise<Array<Person> | string>  => {
  try {
  const stuff = await dynamicsWebApi.retrieveAll(\"accounts\",[\"name\"]);
  const records = stuff.value;
  const options = records?.map(d => ({
    \"value\": d.name,
    \"label\": d.name
  }));
    console.log(options)
    return options
    } catch (error) {
      if (error) {
        console.log(error)
      }
    }
  }

但它在返回选项行上给了我各种各样的错误:

键入 \'{ 值:任何;标签:任何; }[] | undefined\' 不可分配给 输入\'字符串|人[]\'。类型 \'undefined\' 不可分配给类型 \'字符串 |人[]\'

我认为是因为我传回的是一个数组,而 Person 类型不是数组,但我对 TypeScript 了解不多。

同样在 React 组件本身上,我放置加载选项的位置也是错误的:

  <div>
       <AsyncSelect
          cacheOptions
          defaultOptions
          loadOptions={fetchDropDown}
        />

我可以尝试什么来解决这个问题?

    标签: reactjs typescript


    【解决方案1】:

    尝试这个:

    const fetchDropDown = async () : Promise<Array<Person> | undefined >  => {
      try {
      const stuff = await dynamicsWebApi.retrieveAll("accounts",["name"]);
      const records = stuff.value;
      const options = records?.map(d => ({
        "value": d.name,
        "label": d.name
      } as Person));
        console.log(options)
        return options
        } catch (error) {
          if (error) {
            console.log(error)
          }
        }
      }
    

    【讨论】:

    • 它不喜欢 <Person> 类型在地图上的位置。这要死我了!!!哈哈
    • 我已经用 map<Person>(d => ({ 现在我在反应组件上遇到了很多可怕的错误:() => Promise<Person[] | undefined>' is notassignable to type '(inputValue : string, callback: (options: OptionsOrGroups<Person, GroupBase<Person>>) => void) => void | Promise<OptionsOrGroups<Person, GroupBase<...>>>'。输入'Promise<Person[] | undefined>' 不能分配给类型 'void | Promise<OptionsOrGroups<Person, GroupBase<Person>>>'。
    • 我就快到了——请给我最后一击。
    • 任何想法任何人???
    • 抱歉,忘记这是一个 TSX 文件,请使用 as Person 来转换类型。
    猜你喜欢
    • 1970-01-01
    • 2015-11-27
    • 2020-06-21
    • 2015-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多