浏览器自动完成用户名时,不会更新React.js组件的状态

时间:2017-02-21 23:42:09

标签: javascript reactjs

我在React中有以下组件:

class LoginForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {username: '', password: '', redirectToReferrer: false};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    const value = event.target.value;
    const name = event.target.name;

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

  handleSubmit(event) {
    event.preventDefault();
    console.log('A name was submitted: ' + this.state.username);
    Auth.authenticate(this.state.username, this.state.password, () => {
      this.setState({ redirectToReferrer: true })
    })
  }

  render() {
    const { from } = this.props.location.state || { from: { pathname: '/' } }
    const { redirectToReferrer } = this.state

    if (redirectToReferrer) {
      return (
        <Redirect to={from}/>
      )
    }

    return (
      <div>
        <p>You must log in to view the page at {from.pathname}</p>
        <form id='loginForm'>
          <input type="text" name="username" onChange={this.handleChange} />
          <input type="password" name="password" onChange={this.handleChange} />
          <button onClick={this.handleSubmit}>Log in</button>
        </form>
      </div>
    )
  }
}

当我使用浏览器自动完成功能时(而不是键入'admin'我只键入'a'并让浏览器填充其余部分)组件的状态不会更新,并且它提交的值不正确。当我手动输入用户名/密码时,它可以正常工作。我怎样才能解决这个问题?这是很常见的用例...

1 个答案:

答案 0 :(得分:1)

看起来有些browsers have a bug

您可以尝试使用Autofill polyfill解决方法:

  

当浏览器自动填写表单字段时触发更改事件的polyfill