【发布时间】:2024-01-18 04:50:01
【问题描述】:
我花了很多时间来解决这个问题,我决定向人们寻求帮助。
所以基本上我正在尝试的是渲染一个组件。
但在渲染之前我有 2 个数组(labels, notes)。
并使用其中一个(标签),我使用了 map 函数,在其中我使用了 filter 函数来获取我想要传递给渲染组件的唯一元素。
我认为有些帖子与此类似,但略有不同。 并且一些答案说,“当有嵌套的地图功能时,内部地图需要用片段之类的标签包装”但我在其他帖子中发现的并没有包装它...... 如果有人可以帮助我消除我的困惑,请告诉我是否有必要。 Cannot Render Nested Maps In ReactJS React Nested map/forEach wont work
这是我的代码。
let notes = [
{id:1, position:3, content: "apple"},
{id:2, position:2, content: "banana"},
{id:3, position:0, content: "orange"},
]
const labels = ["Discussion questions", "Quotes", "Sensory Ques", "Songs"];
const renderNotes = (notes) => {
return labels.map(label => {
console.log("---" + label + "---")
return (
notes.filter(note => {
// console.log(positionLabels[note.position] + " - " + label);
if (positionLabels[note.position] === label) {
console.log("BINGO");
return (
<CustomComponent
key={note.id}
content={note.content}
/>
)
}
})
)
})
}
在 return 内部我调用这个函数,如下所示
{
renderNotes(notes)
}
当我在测试这样的东西时
const renderNotes = (notes) => {
return positionLabels.map(label => {
return <div>
{
notes.filter(note => {
return (
<div>
TEST
</div>
)
})
}
</div>
})
}
它甚至没有工作,
我不知道objects are not valid as a react child 的错误在说什么。
【问题讨论】:
-
从你的问题中不清楚(对我来说,无论如何)你实际上想要达到什么输出。关于对象作为孩子的错误是因为您的
renderNotes不返回 React 元素或组件的数组,而是一个数组数组,每个数组都是notes的子数组(因此包含普通的 JS 对象)。但是无论如何您都在做一些非常错误的事情,因为您传递给filter的回调似乎返回了一个React 节点,而该回调只需要返回true或false(它只是用于确定要保留哪些元素你的过滤器)。
标签: javascript reactjs filter react-hooks map-function