如何使用TypeScript在useState中设置对象数组

sqxo8psd  于 2023-05-08  发布在  TypeScript
关注(0)|答案(3)|浏览(156)
const res = {
      results: {
        documents: [
          {
            suggestion: 'tes1',
          },
          {
            suggestion: 'test2',
          },
          {
            suggestion: 'test3',
          },
          {
            suggestion: 'test4',
          },
        ],
      },
      meta: {
        request_id: '0e6aa4da',
      },
    };

我想将“res”数据设置为useState()。
于是我创造了Inferface:

interface IResult {
  documents: [
    {
      suggestion: string;
    }
  ];
}

这就是我的useState:

const [querySuggestionResult, setQuerySuggestionResult] = useState<IResult[]>(
    []
  );

我想将这个json文件(响应表单API)设置到useState中,所以我尝试了

setQuerySuggestionResult([{documents: res.results.documents}]);

我也试过

setGuerySuggestionResult(res.results.documents);

an error what ive got
谁能给我解释一下如何设置一个对象数组useState!!

wfveoks0

wfveoks01#

是否可能接口定义不正确?不应该是这样吗?:

interface IResult {
  documents: {
      suggestion: string;
    }[];
}
bwntbbo3

bwntbbo32#

我喜欢这样:
第一个更新的界面:

type SuggestionType = { suggestion: string };
export interface IResult {
  documents: SuggestionType[];
}

第二次更新useState:

const [querySuggestionResult, setQuerySuggestionResult] = useState<IResult>();

最后,我可以像这样设置状态:

setQuerySuggestionResult(res.result);

谢谢你!喜欢它谢雷它!

mitkmikd

mitkmikd3#

下面是另一种步骤更少的方法:

interface Foo {
    id: string;
}
  
const [list, setList] = useState<Array<Foo>>([]);

相关问题