Next.JS/React 对象作为 React 子对象无效

Next.JS/React Objects are not valid as a React child

TL;DR
由于代码中的获取请求,我遇到错误 Error: Objects are not valid as a React child (found: [object Promise])。该项目是用 Typescript 编写的,当我在另一个项目 (Javascript) 中尝试相同的代码片段时,我没有收到错误。

所以我一直在做一个项目,当我尝试通过 fetch 发送 POST 请求时,出现错误 Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.。我认为 fetch 方法中的元数据导致了这个错误,但我认为没有办法解决它。我检查了它是否只是一个错误,所以我将它与我的其他项目中的另一个请求进行了比较,并将其代码复制到我当前的项目中。而且我仍然遇到同样的错误!难道是因为我现在的项目是用打字稿写的?

// This is Typescript
//It's also the same code as my other project.

import axios from 'axios';
export default async function component() {
  const uri = "http://localhost:3000"
  const data = {
    a: 1,
    b: 2,
    c: 3
  }
  async function sendRequest() {
     await fetch(`${uri}/api/getPasswords`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({data}),
    }).then(e => {
      console.log(e);
    }).catch(error => {
      console.log(error)
    })
  }
  return (
    <div>
      <button onClick={sendRequest}>Send POST request</button>
    </div>
  );
}

问题与 Typescript 无关,您正在尝试将 Promise 用作 React 组件,首先,解析 Promise,然后将您需要的数据作为适当的 React 组件发送。

问题是,您在 React 组件 上使用 async。请按照以下步骤操作:

  1. 从 React 组件中删除 async 关键字
  2. 使组件名称以大写开头(组件 -> 组件)
  3. 使用axios代替fetch并使用trycatch(可选
import axios from 'axios'

async function sendRequest() {
  try {
    const res = await axios.post(`${uri}/api/getPasswords`, data)
    console.log(res.data)
  }
  catch(err) {
    console.log(err)
  }
  
}