Firestore,React和Redux的新手。我有一个文档,其中包含一个称为“问题”的地图(请参见下面的图像1中的黄色突出显示)。在此地图中,有问题对象(在图1中带有红色下划线的1、2、3)。我试图动态地解构问题映射数组,将每个问题的数据传递到显示组件中(以使其在用户界面上显示为卡)。
我的代码
导致出现错误,指出“ questions.map不是函数”。
const QuestionList = ({questions}) => { <------ Passed the "questions" map object into this react component.
console.log(questions); <----- Output of console log is found in Image 2. It appears to be correct.
return(
<div className='custom-question-list section'>
{ questions.map(question => { <------ Error states that questions.map is not a function.
console.log(question);
console.log(question.numberOfQuestions);
return (
<div key={question.id}>
<QuestionSummary question={question}/> <----- Simply trying to take each individual question object and pass it into this QuestionSummary component (which helps display the content of that question object.
</div>
)
})
}
</div>
)
}
找到了解决方案 感谢Doug的回应,我找到了解决方案。但是,对于将来可能遇到此问题的读者,我提供了可解决我所遇到问题的代码。您需要使用“ Object.entries”进行映射。
return(
<div className='custom-question-list section'>
{ Object.entries(questions).map(([key, question]) => (
<div key={key}>
<QuestionSummary question={question}/>
</div>
))
}
</div>
)
答案 0 :(得分:1)
我试图动态地解构问题映射数组
没有“映射数组”之类的东西。该字段的类型将为地图或数组。就您而言,它是一个映射,而不是数组。
错误消息告诉您questions
没有名为map的方法。那是因为它不是数组,而是一个普通的旧JavaScript对象,其键/值对与map字段中的键/值对匹配。 (尽管地图的键看起来是数字,但实际上它们只是看起来像数字的字符串。)
如果您要迭代对象中的键/值对,则有很多方法可以执行此操作,如下所述:How to iterate over a JavaScript object?