Javascript 反应:无法读取属性';方法()';方法被绑定时的未定义值
嘿,伙计们,我正在尝试在react中呈现一个表,它在单击时将一行设置为选中状态 单击该行时,我遇到如下错误:Javascript 反应:无法读取属性';方法()';方法被绑定时的未定义值,javascript,node.js,reactjs,Javascript,Node.js,Reactjs,嘿,伙计们,我正在尝试在react中呈现一个表,它在单击时将一行设置为选中状态 单击该行时,我遇到如下错误:uncaughttypeerror:无法读取未定义的属性“setSelected” 关于这一点有很多问题,解决方案似乎是添加行this.setSelected=this.setSelected.bind(this)编码到构造函数中,以便实际可以访问该函数 我已经知道该怎么做了,正如你在下面看到的,我已经做到了,但它仍然给了我错误。我完全被难住了 import React, { Compon
uncaughttypeerror:无法读取未定义的属性“setSelected”
关于这一点有很多问题,解决方案似乎是添加行this.setSelected=this.setSelected.bind(this)将>编码到构造函数中,以便实际可以访问该函数
我已经知道该怎么做了,正如你在下面看到的,我已经做到了,但它仍然给了我错误。我完全被难住了
import React, { Component } from 'react';
class ShowsList extends Component {
constructor(props) {
super(props);
this.state = {selected: {showID: null, i: null}};
this.setSelected = this.setSelected.bind(this);
}
setSelected(event, showID, i) {
this.setState({
selected: {showID, i}
});
console.log(this.state.selected);
}
render() {
return (
<div className="shows-list">
<table className="table">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Location</th>
<th scope="col">Date</th>
<th scope="col">Time</th>
</tr>
</thead>
<tbody>
{this.props.shows.map( function(show, i) {
return (
<tr
key={i}
onClick={(e) => {this.setSelected(e, show._id, i)}}>
<td>{i+1}</td>
<td>{show.eventName}</td>
<td>{show.location}</td>
<td>{show.date}</td>
<td>{show.startTime}</td>
</tr>);
})}
</tbody>
</table>
</div>
);
}
}
export default ShowsList;
import React,{Component}来自'React';
类ShowsList扩展组件{
建造师(道具){
超级(道具);
this.state={selected:{showID:null,i:null};
this.setSelected=this.setSelected.bind(this);
}
setSelected(事件,showID,i){
这是我的国家({
所选:{showID,i}
});
console.log(this.state.selected);
}
render(){
返回(
身份证件
名称
位置
日期
时间
{this.props.shows.map(函数(show,i){
返回(
{this.setSelected(e,show._id,i)}>
{i+1}
{show.eventName}
{show.location}
{show.date}
{show.startTime}
);
})}
);
}
}
导出默认显示列表;
使用function关键字声明的Javascript函数有自己的this
上下文,因此this
内部this.props.shows.map(function(show,i)
不引用类。可以对函数声明使用箭头语法,这将轻松解析this
的值。更改
this.props.shows.map(function(show, i)
到
使用function关键字声明的Javascript函数有自己的this
上下文,因此this
内部this.props.shows.map(function(show,i)
不引用类。可以对函数声明使用箭头语法,这将轻松解析this
的值。更改
this.props.shows.map(function(show, i)
到
哦,哇,这对JS新手来说是个恼人的小把戏。非常感谢,我在写JSX时会记住这一点。哦,哇,这对JS新手来说是个恼人的小把戏。非常感谢,我在写JSX时会记住这一点。