【问题标题】:.map of an object in an array in ReactReact 中数组中对象的 .map
【发布时间】:2016-05-21 22:42:45
【问题描述】:

我正在尝试遍历一个对象,该对象包含数组,其中包含在 React 中的对象,我在 .map 函数上遇到错误。这是.map 函数,后面是this.state 中的对象的样子

.地图:

//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 成为我循环的对象。 day.dayNumberday.dayOfWeek

... .map(function(day, i){
    return(
        <div>
            <div>{day.dayNumber}</div>
            <div>{day.dayOfWeek}</div>
        </div>
    )
}

但是.map 上的错误是this.state[0] 我认为是问题所在。有谁知道我如何访问和循环访问父对象内的数组中的对象?

【问题讨论】:

  • 什么是状态?这是 this.state === 结果吗?在这种情况下,您应该使用 this.state.map 而不是 this.state[0].map
  • 错误是什么?不要听上面的评论,这是错误的。显然你不能通过一个对象映射。
  • 使用 let daysOfWeeks = this.state[0].map(function (day, i){ ... 错误是:Uncaught TypeError: Cannot read property 'map' of undefined
  • 使用 let daysOfWeeks = this.state.map(function (day, i){ ... 错误是:Uncaught TypeError: this.state.map is not a function
  • this.state === 结果

标签: javascript reactjs jsx


【解决方案1】:

试试this.state.result['0'].map(...)

当你有一个像这样的对象时,以数字作为键,即使键是'数字;您将其作为字符串访问。默认情况下,对象键是字符串。

let result = {
    0:[ 
        {dayNumber:1,dayOfWeek:"fri"},
        {dayNumber:2,dayOfWeek:"sat"},
        {dayNumber:3,dayOfWeek:"sun"},
        ...
      ]
}

【讨论】:

    猜你喜欢
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 2021-08-13
    • 2018-09-03
    • 2023-02-04
    • 2021-04-29
    • 2020-08-31
    相关资源
    最近更新 更多