gpt4 book ai didi

javascript - react : Cannot read property 'method()' of undefined when method is bound

转载 作者:太空宇宙 更新时间:2023-11-04 02:55:43 24 4
gpt4 key购买 nike

嘿,大家好,我正在尝试在 React 中渲染一个表格,该表格将一行设置为在单击时的状态下选定。

单击该行时,我收到如下错误:Uncaught TypeError: Cannot read property 'setSelected' of undefined

有很多关于此的问题,解决方案似乎是添加行 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;

最佳答案

使用 function 关键字声明的 JavaScript 函数有自己的 this 上下文,因此 this.props.shows.map( function(show, i) 中的 this 并不引用该类。您可以使用箭头语法进行函数声明,这将宽松地解析 this 的值。更改

this.props.shows.map(function(show, i)

this.props.shows.map((show, i ) => {

关于javascript - react : Cannot read property 'method()' of undefined when method is bound,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48772088/

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