我试图在React中循环包含包含其中对象的数组的对象,并且我在.map
函数上收到错误。以下是.map
函数,后跟this.state
.MAP:
//trying to access January from the object which is 0 starting month
let daysOfWeeks = this.state[0].map(function (day, i){
...
}
以下是该对象的示例:
//0 is January, 1 is February, and so on... inside has objects that have the day number and day of week
let result = {
0:[
{dayNumber:1,dayOfWeek:"fri"},
{dayNumber:2,dayOfWeek:"sat"},
{dayNumber:3,dayOfWeek:"sun"},
...
],
1:[
{dayNumber:1,dayOfWeek:"mon"},
{dayNumber:2,dayOfWeek:"tue"},
{dayNumber:3,dayOfWeek:"wed"},
...
],
2:[
{dayNumber:1,dayOfWeek:"tue"},
{dayNumber:2,dayOfWeek:"wed"},
{dayNumber:3,dayOfWeek:"thur"},
...
],
...
};
//result is in a function that is returned and set state is calling the function and setting state to the object itself -- here is setState:
this.setState(getDaysArray(y,m));
//getDaysArray(y,m) returns that object above
.map
中我想要的是白天成为我循环的对象。 day.dayNumber
和day.dayOfWeek
... .map(function(day, i){
return(
<div>
<div>{day.dayNumber}</div>
<div>{day.dayOfWeek}</div>
</div>
)
}
但我认为问题.map
上的错误this.state[0]
是什么问题。任何人都知道我如何访问和循环父对象内的数组中的对象?
答案 0 :(得分:2)
尝试this.state.result['0'].map(...)
当你有一个像这样的对象时,用一个数字作为键,即使键是一个&#39;数字;你以字符串形式访问它。默认情况下,对象键是字符串。
let result = {
0:[
{dayNumber:1,dayOfWeek:"fri"},
{dayNumber:2,dayOfWeek:"sat"},
{dayNumber:3,dayOfWeek:"sun"},
...
]
}