【问题标题】:React with ES7: Uncaught TypeError: Cannot read property 'state' of undefined [duplicate]与 ES7 反应:未捕获的类型错误:无法读取未定义的属性“状态”[重复]
【发布时间】:2016-05-19 04:42:28
【问题描述】:

每当我在 AuthorForm 的输入框中键入任何内容时,我都会收到此错误 Uncaught TypeError: Cannot read property 'state' of undefined。我在 ES7 中使用 React。

错误发生在ManageAuthorPage 中的setAuthorState 函数的第3 行。不管那行代码是什么,即使我在 setAuthorState 中放了一个 console.log(this.state.author),它也会在 console.log 处停止并指出错误。

在互联网上找不到其他人的类似问题。

这是 ManageAuthorPage 代码:

import React, { Component } from 'react';
import AuthorForm from './authorForm';

class ManageAuthorPage extends Component {
  state = {
    author: { id: '', firstName: '', lastName: '' }
  };

  setAuthorState(event) {
    let field = event.target.name;
    let value = event.target.value;
    this.state.author[field] = value;
    return this.setState({author: this.state.author});
  };

  render() {
    return (
      <AuthorForm
        author={this.state.author}
        onChange={this.setAuthorState}
      />
    );
  }
}

export default ManageAuthorPage 

这里是 AuthorForm 代码:

import React, { Component } from 'react';

class AuthorForm extends Component {
  render() {
    return (
      <form>
                <h1>Manage Author</h1>
        <label htmlFor="firstName">First Name</label>
                <input type="text"
                    name="firstName"
          className="form-control"
                    placeholder="First Name"
          ref="firstName"
          onChange={this.props.onChange}
                    value={this.props.author.firstName}
          />
        <br />

        <label htmlFor="lastName">Last Name</label>
                <input type="text"
                    name="lastName"
          className="form-control"
                    placeholder="Last Name"
          ref="lastName"
                    onChange={this.props.onChange}
          value={this.props.author.lastName}
                    />

                <input type="submit" value="Save" className="btn btn-default" />
            </form>
    );
  }
}

export default AuthorForm

【问题讨论】:

  • 您不得直接修改状态。有asynchronous setState(...) 为此。我正在写这个声明this.state.author[field] = value;。
  • 只需将setAuthorState(event) {...}; 转换为setAuthorState = (event) =&gt; {...}; 否则您必须明确绑定(this)

标签: javascript reactjs ecmascript-6 ecmascript-2016


【解决方案1】:

您必须将事件处理程序绑定到正确的上下文 (this):

onChange={this.setAuthorState.bind(this)}

【讨论】:

  • 我用了你的榜样。谢谢。
  • @Khpalwalk 不客气 :-)
  • 我发现一个更有说服力的方法是使用箭头函数,它会固有地将 this 绑定到函数,我发现它在编写反应代码时特别有用。所以你可以使用 setAuthorState=event=>{...}。将 this 绑定到函数不需要额外的代码行。另外,每次点击这个组件时,都不需要额外的绑定 this 的成本。
  • 我同意,我觉得'this' 似乎躲避了许多开发人员,他们并不完全理解'this' 真正代表什么。我觉得反应开发人员对“这个”有更好的理解,现在这是否纯粹是表面的是另一回事。对于那些不理解“这个”的人应该看看 Kyle Simpsons,你不知道 github 上的 js repo。他的用户名是 getify,其中有几章专门讨论“this”,这将有助于理解“this”在给定上下文中的含义。
  • 是的,谢谢你,它对我有用。我忘了在我的代码中使用绑定。
【解决方案2】:

确保在构造函数中首先调用super()。

你应该为setAuthorState方法设置this

class ManageAuthorPage extends Component {

  state = {
    author: { id: '', firstName: '', lastName: '' }
  };

  constructor(props) {
    super(props);
    this.handleAuthorChange = this.handleAuthorChange.bind(this);
  } 

  handleAuthorChange(event) {
    let {name: fieldName, value} = event.target;

    this.setState({
      [fieldName]: value
    });
  };

  render() {
    return (
      <AuthorForm
        author={this.state.author}
        onChange={this.handleAuthorChange}
      />
    );
  }
}

基于arrow function的另一种选择:

class ManageAuthorPage extends Component {

  state = {
    author: { id: '', firstName: '', lastName: '' }
  };

  handleAuthorChange = (event) => {
    const {name: fieldName, value} = event.target;

    this.setState({
      [fieldName]: value
    });
  };

  render() {
    return (
      <AuthorForm
        author={this.state.author}
        onChange={this.handleAuthorChange}
      />
    );
  }
}

【讨论】:

  • 替代方法对我有用谢谢你的回答
猜你喜欢
  • 2023-03-21
  • 2015-08-19
  • 2022-01-01
  • 1970-01-01
  • 2018-11-09
  • 1970-01-01
  • 2021-06-14
  • 2021-10-13
  • 1970-01-01
相关资源
最近更新 更多