了解如何引用反应组件中的属性

时间:2016-03-13 16:51:07

标签: javascript reactjs react-redux

我无法让这个基本组件识别this对象,无论我尝试什么,我都会收到错误:

  

未捕获的TypeError:无法读取属性' getEvents'未定义的

这是我试图开始工作的代码:

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

为什么this在运行时未定义,我需要做些什么来实际引用我想要的内容?

1 个答案:

答案 0 :(得分: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>
  }
});