javascript – 使用箭头功能反应this.setState会导致控制台出错

我有一个非常简单的表单,我将用户电子邮件存储在组件的状态,并使用onChange函数更新状态.有一个奇怪的事情发生在我的onChange函数用函数更新状态时,我在键入时在控制台中得到两个错误.但是,如果我使用对象更新状态,则不会出现错误.我相信用函数更新是推荐的方法,所以我很想知道为什么我会收到这些错误.

我的组件:

import * as React from 'react';
import { FormGroup, Input, Label } from 'reactstrap';

interface IState {
  email: string;
}

class SignUpForm extends React.Component<{}, IState> {
  constructor(props: {}) {
    super(props);

    this.state = {
      email: ''
    };
  }

  public onEmailChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    this.setState(() => ({ email: event.currentTarget.value }))
  };

  // Using this function instead of the one above causes no errors
  // public onEmailChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  //   this.setState({ email: event.currentTarget.value })
  // };

  public render() {

    return (
      <div>
        <h1>Sign Up</h1>
        <div className='row' style={{ paddingTop: '20px' }}>
          <div className='col-lg-4 offset-lg-4'>
            <form>
              <FormGroup style={{ textAlign: 'left' }}>
                <Label>Email</Label>
                <Input
                  value={this.state.email}
                  onChange={this.onEmailChange}
                  type='text'
                  placeholder='Email Address'
                />
              </FormGroup>
            </form>
          </div>
        </div>
      </div>
    );
  }
}

export default SignUpForm;

我得到的错误消息是:

index.js:2178 Warning: This synthetic event is reused for performance reasons. If you're seeing this, you're accessing the method `currentTarget` on a released/nullified synthetic event. This is a no-op function. If you must keep the original synthetic event around, use event.persist(). See react-event-pooling for more information.

index.js:2178 Warning: A component is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: react-controlled-components

解决方法:

如果状态更新是从当前状态更新(例如递增计数变量),则应使用setState的更新函数版本.

如果您只是像使用事件处理程序那样设置一个全新的值,则不需要使用更新函数版本.您问题中注释掉的版本非常好.

如果要使用更新功能版本,则必须使用event.persist(),以便可以异步使用该事件,或者在调用setState之前简单地提取该值.

public onEmailChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  const { value } = event.currentTarget;
  this.setState(() => ({ email: value }))
};

相关文章

我最大的一个关于TypeScript的问题是,它将原型的所有方法(无...
我对React很新,我正在尝试理解子组件之间相互通信的简洁方法...
我有一个非常简单的表单,我将用户电子邮件存储在组件的状态,...
我发现接口非常有用,但由于内存问题我需要开始优化我的应用程...
我得到了一个json响应并将其存储在mongodb中,但是我不需要的...
我试图使用loadsh从以下数组中获取唯一类别,[{"listing...