Undefined is not an object in .map

时间:2016-10-20 13:13:04

标签: javascript reactjs

I'm working on a react app, and I try to iterate over a data block. The block has a unixtime that I want to do some calculations on, but when I call the function on the object I get the error

      _getTime(time) {
    if (time === 0) {
      return '1';
    } else if (time === 2) {
      return '2';
    } else {
      return 'stuff';
    }
  },

  render: function() {
    return (
      <div className="container-fluid">
        <div className="row">
          <div className="col-md-12 text-center">
              {this.state.daily.map(function(day) {
                return (
                    <div key={day.time} className="key col-md-12">
                    <div className="col-md-3">{this._getTime(day.time)}</div>
                      <div className="col-md-3">{day.icon}</div>
                      <div className="col-md-3">{day.apparentTemperatureMax} / {day.apparentTemperatureMin}</div>
                    </div>
                );
              })}
          </div>
        </div>
      </div>
    );
  },

The problem is this line <div className="col-md-3">{this._getTime(day.time)}</div> and when I place it outside the map function it all works.

Any help will be appreciated

2 个答案:

答案 0 :(得分:1)

That's because this is determined at function call time, not at function write time. Your anonymous function, called by .map() when it iterates the collection for you, doesn't have a this.

There are a couple of ways to solve this, since you're obviously using babel, I can assume you're using ES6, in which case, changing your anonymous function into an arrow function expression, will do the trick:

this.state.daily.map(day => {
  // ...
});

Alternatively, have a look at .bind(), as well as the second argument to .map().

答案 1 :(得分:0)

这是一个函数上下文,而不是组件。在自变量中分配它。

render: function() {
var self = this;

return (
  <div className="container-fluid">
    <div className="row">
      <div className="col-md-12 text-center">
          {self.state.daily.map(function(day) {
            return (
                <div key={day.time} className="key col-md-12">
                <div className="col-md-3">{self._getTime(day.time)}</div>
                  <div className="col-md-3">{day.icon}</div>
                  <div className="col-md-3">{day.apparentTemperatureMax} / {day.apparentTemperatureMin}</div>
                </div>
            );
          })}
      </div>
    </div>
  </div>
);
 }
相关问题