【问题标题】:this is null in one function, not in another of the same classthis 在一个函数中为空,而不是在同一类的另一个函数中
【发布时间】:2017-07-07 18:09:40
【问题描述】:

在我的 React/JS 应用程序中。这是我拥有的 Component 类的一部分:

<p>
            <input
              onChange={ this.handleEmailChange } value={ this.props.email } type='email'
              className={ this.state.error ? 'form-control loginCredentialError shakeElement' : 'form-control' }
              name='email'
              placeholder='Email' required='True'
            />
            <input
              onChange={ this.handlePasswordChange } value={ this.props.password } type='password'
              className={ this.state.error ? 'form-control loginCredentialError shakeElement' : 'form-control' } name='password'
              placeholder='Password' required='True'
            />
          </p>
          <p>
            <Button
              onClick={ (event) => this.handleLoginClick(event) }
              className='btn btn-round-lg btn-round btn-primary btn-block center-block'
            >Sign In</Button>
          </p>

如您所见,我有handleEmailChangehandlePasswordChangehandleLoginClick这三个函数与render 函数属于同一Component

在这个函数中,this 被评估为null,这使得this.setState 失败。

handleEmailChange(event) {
    const value = event.target.value;
    console.log(value);
    this.setState({ email: value });
  } 

然而,在这个函数中this 很好并且有一个值。 setState 效果很好。谁能告诉我为什么这些看似相似的功能有区别?

handleLoginClick(event) {
    event.preventDefault();

    const payload = {
      'email': this.state.email,
      'password': this.state.password,
    };

    this.setState({ communicating: true, error: false, errorServer: false });
...
...
...

【问题讨论】:

  • 是因为箭头函数返回handleLoginClick

标签: reactjs


【解决方案1】:

这里的区别在于绑定。如果您查看如何设置 Button 和 Input 的 onChange,其中一个使用 handleLoginClick 的箭头函数,另一个使用 {this.handleEmailChange}

箭头函数自动将this 绑定到该函数。有两种方法可以解决此问题。要么:

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

onChange = {(event) => handleEmailChange(event)}

这将在函数和您设置其状态的this 之间创建一个绑定。

查看:Difference of .bind() to arrow function () => usage in React 了解有关使用箭头函数或 .bind() 绑定到上下文的更多信息

【讨论】:

  • 啊!是的...我忘了投标。谢谢!
  • 每次都让我着迷!
  • 绑定。那是。没有出价。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-17
相关资源
最近更新 更多