我正在遍历一个对象,它遍历了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',
},
},对于第四个Dropzone,它的id是start-zone,我想呈现一些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渲染得很好,但是我的UI中没有渲染<Title />,PlaceholderButton。
下面是完整的循环
<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渲染特定的标记?
发布于 2020-02-07 07:13:23
我认为问题在于您没有保存.map()的结果并将其传递给render。
在你的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>
) https://stackoverflow.com/questions/60104866
复制相似问题