在 ReactJs 中单击按钮时显示“无法读取未定义的属性编辑名称”

我正在尝试编辑表格中的值并将其放入文本框中。当我单击编辑按钮时,它显示“无法读取未定义的属性编辑名称”。我使用了胖箭头功能。我也在构造函数中使用了绑定,但它有同样的错误。以下是我的代码。单击editName按钮时,它会出错。


class App extends React.Component {

  constructor(props) {

    super(props);

    this.onNameChange = this.onNameChange.bind(this);

    this.onSurnameChange = this.onSurnameChange.bind(this);

    this.onIdChange = this.onIdChange.bind(this);

    this.editName = this.editName.bind(this);

    this.state = {

      data: "",

      name: "",

      surname: "",

      id: ""

    };

  }


  componentDidMount() {

    axios.get("http://localhost:4000/employees").then((response, err) => {

      if (err) {

        console.log("err");

      }

      this.setState(prevstate => ({

        data: response.data

      }));

    });

  }

  handleSumbit(e) {

    axios

      .post("http://localhost:4000/employees", {

        name: this.state.name,

        surname: this.state.surname,

        id: this.state.id

      })

      .then((response, err) => {

        if (err) {

          console.log("Error While Posting Data", err);

        }

        console.log("RESPONSE FROM POST", response);

      });

  }

  onNameChange(e) {

    this.setState({

      name: e.target.value

    });

  }

  onSurnameChange(e) {

    this.setState({

      surname: e.target.value

    });

  }

  onIdChange(e) {

    this.setState({

      id: e.target.value

    });

  }

  editName(value) {

    this.setState({

      name: value

    });

  }

  editSurname(e, value) {

    this.setState({

      surname: value

    });

  }


  render() {

    const { data } = this.state;

    return (

      <div className="container">

        <div>

          <label className="">Name</label>

          <input

            type="text"

            name=""

            value={this.state.name}

            onChange={e => this.onNameChange(e)}

          />

        </div>


哈士奇WWW
浏览 122回答 1
1回答

呼如林

我注意到(正如@DanO 所说)this不是窗口对象,而是在渲染方法中undefined使用内部地图function时。解决方案非常简单,将其更改为箭头函数(首选)或使用Function.prototype.bind.data.map((data,&nbsp;key)&nbsp;=>&nbsp;(<>...</>))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript