gpt4 book ai didi

javascript - 了解如何在 React 组件中引用属性

转载 作者:行者123 更新时间:2023-11-29 14:43:09 25 4
gpt4 key购买 nike

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

Uncaught TypeError: Cannot read property 'getEvents' of undefined

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

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 在运行时未定义,我需要做什么才能真正引用我想要的内容?

最佳答案

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

关于javascript - 了解如何在 React 组件中引用属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35972946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com