简体   繁体   English

如何修复 TypeScript function 类型错误?

[英]How to fix TypeScript function type error?

I have TypeScript code:我有 TypeScript 代码:

const ItemsList: React.FC<any> = async () => {
  const data = await Http.get(url);
  return (
      <ul>
        {data.map(item => {
          return (
            <ItemPreview key={item.id} item={item} />
          );
        })}
      </ul>
  )
}

export default ItemsList

And got error: Type '()=>Promise<JSX.Element>' is not assingable to type 'FC'.并得到错误:类型 '()=>Promise<JSX.Element>' 不能用于类型 'FC'。 Type 'Promise' is missing the folowing properties from type 'ReactElement<any, any>': type, props, key “Promise”类型缺少“ReactElement<any,any>”类型的以下属性:类型、道具、键

Have no idea how to fix it.不知道如何解决它。 What type should it be instead of 'React.FC'?它应该是什么类型而不是“React.FC”?

You're effectively thinking about it the wrong way.你实际上是以错误的方式思考它。 Instead of trying to make React component rendering wait for your data, instead you should be thinking of it in terms of updating state in React.与其试图让 React 组件渲染等待您的数据,不如从更新 React 中的 state 的角度来考虑它。 Your component should just render whatever the current state is:您的组件应该只渲染当前 state 是什么:

return (
  <ul>
    {data.map(item => {
      return (
        <ItemPreview key={item.id} item={item} />
      );
    })}
  </ul>
)

Now, what is data ?现在,什么是data Clearly it's an array, and you also have an asynchronous operation which gets the values for that array.显然它是一个数组,并且您还有一个异步操作来获取该数组的值。 So currently there are a couple potential states:所以目前有几个潜在的状态:

  1. An initial empty array初始空数组
  2. The updated array with data包含数据的更新数组

You'd use React state to track that.您将使用 React state 来跟踪它。 For example:例如:

const [data, setData] = useState([]);

Http.get(url).then(result => {
  setData(result);
});

This first sets data to an empty array, and then in the response from the asynchronous operation updates it to the new data.这首先将data设置为一个空数组,然后在来自异步操作的响应中将其更新为新数据。 Since it's using setState , this will instruct React to update the rendering of the component because state has changed.由于它使用setState ,这将指示 React 更新组件的渲染,因为 state 已更改。

So in this case the UI will first show no results, then momentarily will show the data.所以在这种情况下,用户界面将首先不显示任何结果,然后会立即显示数据。 You can add complexity to this by tracking an "is loading" state of some kind and showing a "loading spinner" or some indication to the user that data is being fetched.您可以通过跟踪某种“正在加载”state 并向用户显示“加载微调器”或某些正在获取数据的指示来增加复杂性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM