启动点击事件方法时,“'this”未定义

时间:2019-09-04 02:27:29

标签: reactjs

我很困惑,因为当我用值填充this.state.seats时,它正确地呈现了DOM中的所有组件。但是,当我单击该组件(按钮)时,它返回到App.js并显示给我:

  

未捕获的TypeError:无法读取未定义的属性“状态”

即使此状态属性中的组件也显示在DOM中!

请,有人知道会发生什么吗?

enter image description here

App.js

import React, { Component } from "react";
import "./App.css";
import Seats from "./Seats";

class App extends Component {
  state = {
    seats: this.initializeSeats()
  };

  initializeSeats() {
    let seats = [];
    let count = 5;
    for (let a = 0; a < count; a++) {
      for (let b = 0; b < count; b++) {
        seats.push({ key: '' + a + b, reserved: false });
      }
    }
    seats.find(s => s.key === '00').reserved = true;
    return seats;
  }

  onClickSeat(e) {
    const seats = [...this.state.seats];
    let seat = seats.find(s => s.key === e.target.value);
    seat.reserved = !seat.reserved;
    console.log(seat.reserved);
    this.setState({ seats: seats });
  }

  render() {
    return (
      <div>
        <h3>Kinosál</h3>
        <Seats
          seats={this.state.seats}
          onClickSeat={this.onClickSeat}
        />
      </div>
    );
  }
}
export default App;

Seats.jsx

import React, { Component } from "react";
import Seat from "./Seat";

class Seats extends Component {
  render() {
    const result = [];
    for (let seat of this.props.seats) {
      if (!seat.reserved) {
        result.push({ key: seat.key, reserved: seat.reserved });
      }
    }
    return (
      <div>
        {result.map(seat => (
          <Seat
            key={seat.key}
            onClick={this.props.onClickSeat}
            seat={seat}
          />
        ))}
      </div>
    );
  }
}
export default Seats;

Seat.jsx

import React, { Component } from "react";
import uuid from 'uuid';

class Seat extends Component {
  render() {
    const { seat, onClick } = this.props;
    return (
      <div>
        <button onClick={onClick} key={uuid.v4()} value={seat.key}>{seat.key}</button>
      </div>
    );
  }
}
export default Seat;

1 个答案:

答案 0 :(得分:1)

看看https://reactjs.org/docs/handling-events.html

  

您必须小心JSX回调中的含义。在JavaScript中,默认情况下不绑定类方法。如果忘记绑定this.handleClick并将其传递给onClick,则在实际调用该函数时将无法定义。

您必须将onClickSeat绑定到App的{​​{1}}类实例,您可以使用下面的类箭头语法来实现。

this

一旦这样做,一切都会正常!它还说明了为什么您可以看到DOM中的组件,但是 onClickSeat = (e) => { const seats = [...this.state.seats]; let seat = seats.find(s => s.key === e.target.value); seat.reserved = !seat.reserved; console.log(seat.reserved); this.setState({ seats: seats }); } 的状态未定义(这是因为onClickSeat中的this没有像您期望的那样引用类实例)< / p>