dangerouslySetInnerHTML显示映射数据上的对象



我尝试从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)
}} />
</>
);
}

最新更新