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

标签 asp.net-mvc reactjs react-native asp.net-mvc-4 asp.net-core

我有以下 .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/

相关文章:

javascript - 在 React 中使用 Google Place Autocomplete API

node.js - 使用 sequelize 根据 id 更新行的值会产生 404 错误

javascript - 如何在React Native中从另一个函数调用一个函数

asp.net-mvc - 我如何在 asp.net mvc 方法中读取 cookie?

c# - 如何在网页中显示我的 Wordpress 站点的最新博客条目?

javascript - 如何使用react-camera将jpg图像发送到服务器?

sockets - 没有可用的交通工具

javascript - 如何在 Javascript 中使用新日期执行条件?

c# - 目录不存在。参数名称 : directoryVirtualPath

javascript - 行复选框在 jQuery 数据表中不起作用