承诺< element>不是有效的JSX元素,可以转换Promise< element>到元素

发布于 2025-02-08 16:41:15 字数 1658 浏览 0 评论 0原文

我正在尝试使用item组件,但是它给出了此错误:

(alias) const Item: (id: string) => Promise<JSX.Element>
import Item
Type '{}' is not assignable to type 'string'.ts(2322)
'Item' cannot be used as a JSX component.
  Its return type 'Promise<Element>' is not a valid JSX element.
    Type 'Promise<Element>' is missing the following properties from type 'ReactElement<any, any>': type, props, key ts(2786)

项目组件是这样的:

const Item = async (id: string) => {    
    const itemData = await getItemData(id);

    return (<Button className="item">
        <ItemContent name={itemData.name} description={itemData.description} />
    </Button>);
}

getItemdata函数是这样:


async function getItemData(item: string) {

    if (item === "") {
        return {
            name: "Error",
            description: "Couldn't fetch the latest items :( ..."
        }
    }

    const itemData = fetch("/api/items/getItem/", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            id: item
        })
    })
    .catch(err => {
        console.error(err);
        throw new Error("Failed to get item data");
    });

    const res = (await itemData).json();
    return res;

}

我该怎么做才能转换promise&lt; element&gt; to element,我尝试了。我尝试键入函数,它也不起作用,每当我尝试使用item组件时,它就会出现错误。

如果很重要,我将使用react next.js与打字稿

I'm trying to use the Item component, but it gives this error:

(alias) const Item: (id: string) => Promise<JSX.Element>
import Item
Type '{}' is not assignable to type 'string'.ts(2322)
'Item' cannot be used as a JSX component.
  Its return type 'Promise<Element>' is not a valid JSX element.
    Type 'Promise<Element>' is missing the following properties from type 'ReactElement<any, any>': type, props, key ts(2786)

The Item component is like this:

const Item = async (id: string) => {    
    const itemData = await getItemData(id);

    return (<Button className="item">
        <ItemContent name={itemData.name} description={itemData.description} />
    </Button>);
}

The getItemData function is like this:


async function getItemData(item: string) {

    if (item === "") {
        return {
            name: "Error",
            description: "Couldn't fetch the latest items :( ..."
        }
    }

    const itemData = fetch("/api/items/getItem/", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            id: item
        })
    })
    .catch(err => {
        console.error(err);
        throw new Error("Failed to get item data");
    });

    const res = (await itemData).json();
    return res;

}

What can I do to convert Promise<Element> to Element, I tried .then(res => res.json()), it doesn't work, I tried typing the functions, it doesn't work either, whenever I try to use the Item component it just gives the error.

If it's important, I'm using React Next.js with Typescript

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

长安忆 2025-02-15 16:41:16

要与TypeScript一起使用异步服务器组件,请确保您使用Typescript 5.1.3或更高版本以及 @types/eack 18.2.8或更高版本。
它来自官方下一个文档

”在此处输入映像说明”

另外我还添加typescript角色:

{/* @ts-expect-error Async Server Component */}

“在此处输入图像说明”

To use an async Server Component with TypeScript, ensure you are using TypeScript 5.1.3 or higher and @types/react 18.2.8 or higher.
it is from official next documentation

enter image description here

Also I add typescript role before component:

{/* @ts-expect-error Async Server Component */}

enter image description here

如痴如狂 2025-02-15 16:41:16

使用此命令安装最新版本的Typescript和 @type/react:

npm install typescript@latest @types/react@latest

它将解决问题。
安装后,请确保重新启动您的代码编辑器。这解决了问题。
另外,如果组件在顶部具有“使用客户端”,则将其删除。

Install the latest version of typescript and @types/react with this command:

npm install typescript@latest @types/react@latest

it'll fix the issues.
After the installation make sure to restart your code editor. This solved the issue.
Also if the component has "use client" at the top remove it.

与酒说心事 2025-02-15 16:41:16

确保您在page.tsx中使用getItemdata函数,这是因为JSX或TSX函数不支持异步。在这里,我给您一个示例,假设搜索是从参数完成的

async function getItemData(item: string) {

    if (item === "") {
        return {
            name: "Error",
            description: "Couldn't fetch the latest items :( ..."
        }
    }

    const itemData = fetch("/api/items/getItem/", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            id: item
        })
    })
    .catch(err => {
        console.error(err);
        throw new Error("Failed to get item data");
    });

    const res = (await itemData).json();
    return res;

}
export default async function Page({params}: Props) {
const data = await getItemData(params)
  return (
    <>
      <Item data={data} />
    </>
  )
}
const Item = (data: ItsProps) => {    
    return (
    <Button className="item">
        <ItemContent name={data.name} description={data.description} />
    </Button>);
}

Make sure you are using the GetItemData function in the page.tsx, this is because the JSX or TSX functions do not support asynchrony. Here I give you an example assuming that the search is done from the parameter

async function getItemData(item: string) {

    if (item === "") {
        return {
            name: "Error",
            description: "Couldn't fetch the latest items :( ..."
        }
    }

    const itemData = fetch("/api/items/getItem/", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({
            id: item
        })
    })
    .catch(err => {
        console.error(err);
        throw new Error("Failed to get item data");
    });

    const res = (await itemData).json();
    return res;

}
export default async function Page({params}: Props) {
const data = await getItemData(params)
  return (
    <>
      <Item data={data} />
    </>
  )
}
const Item = (data: ItsProps) => {    
    return (
    <Button className="item">
        <ItemContent name={data.name} description={data.description} />
    </Button>);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文