问题
I have a react component in gatsbyJS that is mapping through a graphQL query, so far it works however I have introduced a inline fragment in the graphQL query two of them actually and I want to check if fragment exists then output the code otherwise all my maps are outputting empty div's after real content is outputted. I didn't include the whole query or all the code for brevity.
Hopefully someone can help, Thanks!
Here is my map and jsx
{data.datoCmsProject.projectBlock.map(projectEntry => {
return (
<>
// I want to check here if DatoCmsProjectBlockGrid fragment exists then render below
<BlockGridWrapper>
<BlockGrid key={projectEntry.id}>
<div>{projectEntry.titleOfGridSection}</div>
</BlockGrid>
</BlockGridWrapper>
// end check for DatoCmsProjectBlockGrid
// I want to check here if DatoCmsSingleProjectBlockContent fragment exists, then render below
<NewBlock key={projectEntry.id}>
<img key={imageEntry.originalId} src={imageEntry.url}/>
</NewBlock>
//end check for DatoCmsSingleProjectBlockContent
...
Here is my query
projectBlock{
... on DatoCmsSingleProjectBlockContent {
id
titleOfSection
descriptionOfImage
descriptionToggle
wideView
imageTextSide
imageAssetHideShow
imageAsset{
url
originalId
}
}
... on DatoCmsProjectBlockGrid {
id
titleOfGridSection
}
}
回答1:
You can utilize the __typename field to determine the type of the returned object and then render the appropriate component.
projectBlock {
__typename
... on DatoCmsSingleProjectBlockContent {
id
# other fields
}
... on DatoCmsProjectBlockGrid {
id
# other fields
}
}
In this case, __typename will resolve to DatoCmsSingleProjectBlockContent, DatoCmsProjectBlockGrid or whatever other possible types for the projectBlock field. If there are other possible types that you don't want to render, you should either filter the array first or utilize reduce instead of map to the same effect:
data.datoCmsProject.projectBlock
.filter(({ __typename }) => __typename === 'DatoCmsSingleProjectBlockContent' || __typename === 'DatoCmsProjectBlockGrid')
.map(projectEntry => {
if (projectEntry.__typename === 'DatoCmsSingleProjectBlockContent') {
return <BlockGridWrapper/>
}
return <NewBlock/>
})
来源:https://stackoverflow.com/questions/59585841/graphql-inline-fragments-check-if-exist-and-then-output-in-a-map