简体   繁体   中英

Undefined is not an object in .map

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

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() .

this is a function context, not component. Assign this in self variable.

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>
);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM