NextJS13, why I get 'Error: Objects are not valid as a React child (found: [object Promise]).'?

huangapple go评论73阅读模式
英文:

NextJS13, why I get 'Error: Objects are not valid as a React child (found: [object Promise]).'?

问题

I see you want the code to be translated. Here's the translation of the code you provided:

我对这个错误感到非常困扰不知道如何修复它这是我的代码

'使用客户端'
import React, { useState } from 'react'
import AnimatedDiv from '../../../(shop)/(components)/animatedDiv'
import ProfileSection from './profileSection'
import AccountSection from './accountSection'
import SubscriptionSection from './subscriptionSection'

const SettingsPageOrchestrator = () => {
  const [renderedSection, setRenderedSection] = useState('Profile')

  return (
    <div >
      <div >
        <button          
          onClick={() => setRenderedSection('Profile')}
        >
          Profile
        </button>
        <button
          onClick={() => setRenderedSection('Account')}
        >
          Account
        </button>
        <button
          onClick={() => setRenderedSection('Subscription')}
        >
          Subscription and billing
        </button>
      </div>
      <InnerSection section={renderedSection} />
    </div>
  )
}

const InnerSection = ({ section }) => {
  return (
    <div>
      {section === 'Profile' && (
        <AnimatedDiv>
          <ProfileSection />
        </AnimatedDiv>
      )}
      {section === 'Account' && (
        <AnimatedDiv>
          <AccountSection />
        </AnimatedDiv>
      )}
      {section === 'Subscription' && (
        <AnimatedDiv>
          <SubscriptionSection />
        </AnimatedDiv>
      )}
    </div>
  )
}

export default SettingsPageOrchestrator

这是出错的组件:

import React from 'react'
import ProfileContent from './profileContent'
import ProfileSkeletron from './profileSkeletron'
import { SETTINGS_PROFILE_USER } from '../../../../apiUtils/costants'

import { getAuthenticatedServerSide } from '../../../../apiUtils/utils'
import { getServerSession } from 'next-auth'
import { authOptions } from '../../../../pages/api/auth/[...nextauth]'

const ProfileSection = async () => {
  const session = await getServerSession(authOptions)
  const data = await getAuthenticatedServerSide(
    session?.user?.access_token,
    SETTINGS_PROFILE_USER
  )

  return (
    <div>
      <ProfileContent data={data} />
    </div>
  )
}

export default ProfileSection

我不明白为什么会出现这个错误 'Unhandled Runtime Error 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.'。我错在哪里?


<details>
<summary>英文:</summary>
I&#39;m freaking out about this error and don&#39;t understand how to fix it. Here is my code :

'use client'
import React, { useState } from 'react'
import AnimatedDiv from '../../../(shop)/(components)/animatedDiv'
import ProfileSection from './profileSection'
import AccountSection from './accountSection'
import SubscriptionSection from './subscriptionSection'

const SettingsPageOrchestrator = () => {
const [renderedSection, setRenderedSection] = useState('Profile')

return (
<div >
<div >
<button
onClick={() => setRenderedSection('Profile')}
>
Profile
</button>
<button
onClick={() => setRenderedSection('Account')}
>
Account
</button>
<button
onClick={() => setRenderedSection('Subscription')}
>
Subscription and billing
</button>
</div>
<InnerSection section={renderedSection} />
</div>
)
}

const InnerSection = ({ section }) => {
return (
<div>
{section === 'Profile' && (
<AnimatedDiv>
<ProfileSection />
</AnimatedDiv>
)}
{section === 'Account' && (
<AnimatedDiv>
<AccountSection />
</AnimatedDiv>
)}
{section === 'Subscription' && (
<AnimatedDiv>
<SubscriptionSection />
</AnimatedDiv>
)}
</div>
)
}

export default SettingsPageOrchestrator


This is the component where I get the error :

import React from 'react'
import ProfileContent from './profileContent'
import ProfileSkeletron from './profileSkeletron'
import { SETTINGS_PROFILE_USER } from '../../../../apiUtils/costants'

import { getAuthenticatedServerSide } from '../../../../apiUtils/utils'
import { getServerSession } from 'next-auth'
import { authOptions } from '../../../../pages/api/auth/[...nextauth]'

const ProfileSection = async () => {
const session = await getServerSession(authOptions)
const data = await getAuthenticatedServerSide(
session?.user?.access_token,
SETTINGS_PROFILE_USER
)

return (
<div>
<ProfileContent data={data} />
</div>
)
}

export default ProfileSection


I didn&#39;t understand why I get this error &#39;Unhandled Runtime Error
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.&#39;
Where am I wrong ?
</details>
# 答案1
**得分**: 0
React在抱怨这个问题:
```javascript
const ProfileSection = async () => {
-------------------------^

未处理的运行时错误错误:对象不能作为React子元素(发现:[object Promise])

您的组件是async的,这意味着它返回一个Promise,但React无法处理它。

现在,可能最简单的解决方案是将async函数移到useEffect内部,然后使用它返回的数据设置本地状态。然后您可以在组件中使用该状态。

从长远来看,您可能需要考虑在何时需要该数据,或者是否要将其提供给多个组件。在这种情况下,您可能需要使用全局状态解决方案(有很多选择),或者使用自定义钩子来包含该具有状态的逻辑以便重用。

import { useEffect, useState } from 'react';

function ProfileSection() {

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

  useEffect(() => {
    async function getData() {
      const session = await getServerSession(authOptions)
      const data = await getAuthenticatedServerSide(
        session?.user?.access_token,
        SETTINGS_PROFILE_USER
      );
      setData(data);
    }
    getData();
  }, []);

  if (!data) return <div>No profile</div>;

  return (
    <div>
      <ProfileContent data={data} />
    </div>
  );

}

export default ProfileSection
英文:

React is complaining about this:

const ProfileSection = async () =&gt; {
-------------------------^

> Unhandled Runtime Error Error: Objects are not valid as a React child (found: [object Promise])

Your component is async which means it's returning a promise but React can't work with that.

Probably the easiest solution (for now) would be to move the async function inside a useEffect, and then set local state with the data it returns. You can then use that state in your component.

In the long term you may want to think about at what point you want that data available, or if it's going to be available to more than one component. At which point you may need to reach for global state solution (of which there are many), or perhaps a custom hook to contain that stateful logic for reuse.

import { useEffect, useState } from &#39;react&#39;;
function ProfileSection() {
const [ data, setData ] = useState(null);
useEffect(() =&gt; {
async function getData() {
const session = await getServerSession(authOptions)
const data = await getAuthenticatedServerSide(
session?.user?.access_token,
SETTINGS_PROFILE_USER
);
setData(data);
}
getData();
}, []);
if (!data) return &lt;div&gt;No profile&lt;/div&gt;;
return (
&lt;div&gt;
&lt;ProfileContent data={data} /&gt;
&lt;/div&gt;
);
}
export default ProfileSection

huangapple
  • 本文由 发表于 2023年4月19日 16:00:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76052035.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定