ReactJs - 在 onclick 事件中访问状态

ReactJs - accessing state in the onclick event

我有以下.jsx文件,试图在删除超链接的onclick事件中访问state对象上的空缺属性,但一直得到

"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)
}

https://fetch-result.stackblitz.io

const dd = [
  {
    "id": 1,
    "title": "Vacancy 1",
    "currency": "$",
    "minSalary": 1000,
    "maxSalary": 10000
  },
  {
    "id": 2,
    "title": "Vacancy 2",
    "currency": "$",
    "minSalary": 2000,
    "maxSalary": 20000
  },
  {
    "id": 3,
    "title": "Vacancy 3",
    "currency": "$",
    "minSalary": 3000,
    "maxSalary": 30000
  },
  {
    "id": 4,
    "title": "Vacancy 4",
    "currency": "$",
    "minSalary": 4000,
    "maxSalary": 40000
  },
]

class Vacancy extends React.Component {
  constructor(props) {
    super(props);
    this.state = { vacancies: dd, loading: true };
  }

  handleDelete = (id) => {
    debugger;
    console.log(id)
    let vacancies = this.state.vacancies;
  }



  render() {
    let loadVacancies = [];
    let vacancies = this.state.vacancies;

    loadVacancies.push(
      <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>
    )

    let contents = this.state.loading ? loadVacancies  : "";

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

从渲染中的 handleDelete 和 loadVacancies 声明中删除关键字 static,更改为 this.loadVacancies

class 职位空缺 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

    }

    handleDelete(id) {

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

    }

    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>
            : this.loadVacancies(this.state.vacancies);

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

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