gpt4 book ai didi

asp.net-mvc - ReactJs - 访问 onclick 事件中的状态

转载 作者:行者123 更新时间:2023-12-02 03:09:38 26 4
gpt4 key购买 nike

我有以下 .jsx 文件,尝试在删除超链接的 onclick 事件中访问状态对象上的空缺属性,但不断获取

"cannot read property 'vacancies' of undefined" error

class Vacancy extends React.Component {

constructor(props) {

super(props);
this.state = { vacancies: [], loading: true };

fetch('/api/Vacancy/Vacancies')
.then(response => response.json())
.then(data => {
this.setState({ vacancies: data, loading: false });
});

//this.handleDelete = this.handleDelete.bind(this);//If uncomment, throws - Cannot read property 'bind' of undefined

}

static handleDelete(id) {

debugger;
var vacancies = this.state.vacancies;//Cannot read property 'vacancies' of undefined

}

static loadVacancies(vacancies) {
return (
<table className='table table-striped'>
<thead>
<tr>
<th>Title</th>
<th>Min Salary</th>
<th>Max Salary</th>
</tr>
</thead>
<tbody>
{vacancies.map(v =>
<tr key={v.id}>
<td>{v.title}</td>
<td>{v.currency} {v.minSalary}</td>
<td>{v.currency} {v.maxSalary}</td>
<td>
<a href="#" onClick={(id) => this.handleDelete(v.id)}>Delete</a>
</td>
</tr>
)}
</tbody>
</table>
);
}

render() {

let contents = this.state.loading
? <p><em>Loading...</em></p>
: Vacancy.loadVacancies(this.state.vacancies);

return (
<div>
{contents}
</div>
);
}
}

const containerElement = document.getElementById('content');
ReactDOM.render(<Vacancy />, containerElement);

最佳答案

您已将handleDelete声明为静态方法,因此handleDelete在实例上永远不可用。

您可以将其用作

handleDelete = ()=>{//write the handling here}

constructor(props){
super(props)
this.handleDelete = this.handleDelete.bind(this)
}

关于asp.net-mvc - ReactJs - 访问 onclick 事件中的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57991179/

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