【问题标题】:Understanding how to refer to properties in react components了解如何在 React 组件中引用属性
【发布时间】:2016-03-13 16:51:06
【问题描述】:

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

未捕获的类型错误:无法读取未定义的属性“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 在运行时未定义,我需要做什么才能真正引用我想要的内容?

【问题讨论】:

    标签: javascript reactjs react-redux


    【解决方案1】:

    arrow function(=&gt;)改成普通函数,因为箭头函数没有自己的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>
      }
    });
    

    【讨论】:

      猜你喜欢
      • 2013-03-31
      • 2020-07-24
      • 2020-11-01
      • 2017-07-02
      • 1970-01-01
      • 2018-01-04
      • 2017-09-25
      • 2019-01-06
      • 2021-01-08
      相关资源
      最近更新 更多