危险地SetInnerHTML 显示映射数据上的对象

问题描述

我尝试从 GraphQL 数据中获取一些值。然后,我想通过
显示<div dangerouslySetInnerHTML={{ __html: ExtendedProfileShow }} />

然后,我得到了 [object Object],[object Object],[object Object]

这是我的代码

错误文件

export default function Profile({ profileData }) {
    const ExtendedProfileShow = [
        profileData.businessInfo.extendedProfile.map((showExtendedProfile) => (
            <div key={showExtendedProfile.title}>
                {showExtendedProfile.title} <br/> {showExtendedProfile.info}    
            </div>
        ))
    ]

    return (
        <> 
          <div dangerouslySetInnerHTML={{ __html: ExtendedProfileShow }} />
        </>
    );
}

我的 api.js:

export async function getAllBusinessProfiles() {
    const data = await fetchAPI(
      `
      query AllProfiles {
        businessProfiles(where: {orderby: {field: DATE,order: ASC}}) {
          edges {
            node {
              date
              title
              slug
              link
              uri
              businessInfo {
                name
                title
                company
                image {
                  mediaItemUrl
                  altText
                }
                highlight
                phone
                city
                country
                facebook
                linkedin
                instagram
                email
                website
                profiles {
                  profile
                  profileInfo
                }
                extendedProfile {
                  title
                  info
                }
              }
            }
          }
        }
      }
      
      `
    );
    return data?.businessProfiles;
};

数据具有 HTML 元素,例如 - <p> Test test </p> 并且它也应该执行标签

这里可能有什么错误?谢谢。

解决方法

在这种情况下,甚至不需要使用 dangerouslySetInnerHTML。您可以直接传递您生成的 JSX。

export default function Profile({ profileData }) {
    const ExtendedProfileShow = [
        profileData.businessInfo.extendedProfile.map((showExtendedProfile) => (
            <div key={showExtendedProfile.title}>
                {showExtendedProfile.title} <br/> {showExtendedProfile.info}    
            </div>
        ))
    ]

    return (
        <> 
            <div>{ExtendedProfileShow}</div>
        </>
    );
}

但是,如果出于某种原因您真的想使用 dangerouslySetInnerHTML,您可以使用 ReactDOMServer.renderToStaticMarkup 将您的 JSX 转换为字符串。

import ReactDOMServer from 'react-dom/server'

export default function Profile({ profileData }) {
    const ExtendedProfileShow = [
        profileData.businessInfo.extendedProfile.map((showExtendedProfile) => (
            <div key={showExtendedProfile.title}>
                {showExtendedProfile.title} <br/> {showExtendedProfile.info}    
            </div>
        ))
    ]

    return (
        <> 
            <div dangerouslySetInnerHTML={{
                __html: ReactDOMServer.renderToStaticMarkup(ExtendedProfileShow)
            }} />
        </>
    );
}