3

I can not get this basic component to recognize the this object, whatever I try I get the error:

Uncaught TypeError: Cannot read property 'getEvents' of undefined

This is the code im trying to get working:

import React from 'react'
import PureRenderMixin from 'react-addons-pure-render-mixin';
import { connect } from 'react-redux';
import ListGroup from 'react-bootstrap/lib/ListGroup';
import ListGroupItem from 'react-bootstrap/lib/ListGroupItem';

export const Selector1 = React.createClass({
  mixins: [PureRenderMixin],

  getEvents: () => this.props.eventTypes || [{name: "NO EVENTS!"}],

  render: _ =>
      <ListGroup>
        {this.getEvents().map(event =>
          <ListGroupItem>{event.name}</ListGroupItem>
        )}
      </ListGroup>
});

function mapStateToProps(state) {
  return {
    eventTypes: state.get('eventTypes')
  };
}

export const Selector1Container = connect(mapStateToProps)(Selector1);

Why is this undefined at runtime and what do I need to do for this to actually refer to what I want?

4

1 回答 1

2

arrow function将( )更改=>为普通函数,因为箭头函数没有自己的this

export const Selector1 = React.createClass({
  mixins: [PureRenderMixin],

  getEvents() {
    return this.props.eventTypes || [{name: "NO EVENTS!"}]
  },

  render() {
    return <ListGroup>
      {this.getEvents().map(event =>
        <ListGroupItem>{event.name}</ListGroupItem>
       )}
    </ListGroup>
  }
});
于 2016-03-13T16:59:27.717 回答