[英]Loop through object, if condition is met, return additional mark up
我正在循环一个对象,它循环了DropZone
对象 4 次,
每个DropZone
都有一个 id
dropZones: {
'zone-1': {
id: 'zone-1',
title: 'zone-1',
info: 'Strongest',
items: [
{ id: 1, content: 'I am label 1' },
{ id: 2, content: 'I am label 2' },
],
maxItems: 3,
color: '#8bea97',
},
'zone-2': {
id: 'zone-2',
title: 'zone-2',
info: 'Strong',
items: [],
maxItems: 5,
color: '#bef7c6',
},
'zone-3': {
id: 'zone-3',
title: 'zone-3',
info: 'Weakest',
items: [{ id: 4, content: 'I am label 4' }],
color: '#e6ffe9',
},
'start-zone': {
id: 'start-zone',
title: 'Inactive',
info: 'Inactive',
items: [
{ id: 5, content: 'I am label 5' },
{ id: 6, content: 'I am label 6' },
{ id: 7, content: 'I am label 7' },
{ id: 8, content: 'I am label 8' },
{ id: 9, content: 'I am label 9' },
],
color: 'white',
},
},
对于 ID 为start-zone
的第 4 个 Dropzone,我想呈现一些 JSX 标记。
我检查 dropzone 是否具有start-zone
的 zoneId ,然后循环遍历它以呈现我的标记。
if (zoneId === 'start-zone') {
dropZone.items.map(item => (
<Placeholder>
<Title>Labels</Title>
<PlaceholderButton type="button" onClick={() => setShowInput(!showInput)}>
+
</PlaceholderButton>
<Item
draggable
onDrag={() => {
setDragSource(dropZone.id)
setDraggedItem(item)
}}
key={item.id}
>
{item.content}
</Item>
</Placeholder>
))
}
我的Item
渲染得很好。 但是<Title />
, PlaceholderButton
没有在我的 UI 中呈现。
这是完整的循环
<div onDrop={onDrop}>
{Object.keys(currentAnswer).length !== 0
? zoneOrder.map(zoneId => {
const dropZone = currentAnswer[zoneId]
if (zoneId === 'start-zone') {
dropZone.items.map(item => (
<Placeholder>
<Title>Labels</Title>
<PlaceholderButton type="button" onClick={() => setShowInput(!showInput)}>
+
</PlaceholderButton>
<Item
draggable
onDrag={() => {
setDragSource(dropZone.id)
setDraggedItem(item)
}}
key={item.id}
>
{item.content}
</Item>
</Placeholder>
))
}
return (
<DropZone
onDragOver={event => onDragOver(event)}
data-droppable
id={dropZone.id}
key={dropZone.id}
onDragLeave={onDragLeave}
>
{dropZone.items.map(item => (
<Item
draggable
onDrag={() => {
setDragSource(dropZone.id)
setDraggedItem(item)
}}
key={item.id}
>
{item.content}
<DropZoneLabel>{dropZone.title}</DropZoneLabel>
</Item>
))}
</DropZone>
)
})
: null}
我的控制台中没有错误表明为什么会发生这种情况。 有没有更好的方法来为我的DropZone
渲染特定标记?
我认为问题在于您没有保存 .map() 的结果并将其传递给渲染。
在你的 if 里面,你做
if (zoneId === 'start-zone') {
dropZone.items.map(item => (
...
)
但是你没有将它分配给一个变量,所以产生的 JSX 会被丢弃。
尝试
let result;
if (zoneId === 'start-zone') {
result = dropZone.items.map(item => (
...
)
}
return (
<DropZone
onDragOver={event => onDragOver(event)}
data-droppable
id={dropZone.id}
key={dropZone.id}
onDragLeave={onDragLeave}
>
{result}
</DropZone>
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.