【问题标题】:Why changing state from false to true throws a Warning为什么将状态从 false 更改为 true 会引发警告
【发布时间】:2019-06-16 22:07:57
【问题描述】:

我正在创建一个简单的客户端登录表单。当用户登录时,currentAdmin 状态变为 true(默认为 false)。出于某种原因,setState 会引发警告 A 组件正在更改类型为 submit 的不受控制的输入以进行控制。输入元素不应从不受控切换到受控(反之亦然)。决定在组件的生命周期内使用受控输入元素还是不受控输入元素。

我尝试在 Header.js 中使用 refs,但这没有帮助。

App.js

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

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      currentAdmin: false
    }
  }
  onSignIn = (login, password) => {
    if (login === 'admin' && password === '123') {
      this.setState({
        currentAdmin: true
      })
    }
  }

  onSignout = () => {
    this.setState({
      currentAdmin: false,
    })
  }
render() {
    return (
      <div>
          <Header
            onSignin={this.onSignIn.bind(this)}
            onSignout={this.onSignout.bind(this)}
            currentAdmin={this.state.currentAdmin}
          />
      </div>
    )
  }
}
export default App.js;

Header.js

import React, {Component} from 'react';
import './Header.css';

class Header extends Component {
  constructor(props) {
    super(props);
    this.handleSignin = this.handleSignin.bind(this);
    this.handleSignout = this.handleSignout.bind(this);
  }

  handleSignin(e) {
    e.preventDefault();
    let login = this.refs.login.value;
    let password = this.refs.password.value;
    this.props.onSignin(login, password);
  }

  handleSignout(e) {
    e.preventDefault();
    this.props.onSignout();
  }

  render() {
    if (this.props.currentAdmin === false) {
       return (
        <div className='header'>
          <a href='google.com' className='logo'>ToDoApp</a>
          <form className='login' onSubmit={this.handleSignin}>
            <input type='text' placeholder='login' ref='login'/>
            <input type='password' placeholder='password' ref='password'/>
            <input type='submit' value='Log in'/>
           </form>
        </div>
      );
    } else {
      return (
        <div className='header'>
          <a href='google.com' className='logo'>ToDoApp</a>
          <form className='login' onSubmit={this.handleSignout}>
            <input type='submit' value='Log out'/>
          </form>
        </div>
      );
    }
  }
}

export default Header;

这会引发警告。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    您需要在input 上使用defaultValue 属性,而不是value。查看文档here

    作为其他选项 - 您可能希望将 input type="submit" 替换为 button type="submit"

    【讨论】:

    • 这是最好的选择&lt;button type="submit"&gt;Login&lt;/button&gt;
    【解决方案2】:

    ALexand Tovmach 提供了完美的(就我个人而言)答案。我应该把&lt;input type='submit' value='Log in/&gt;改成&lt;button type='submit'&gt;Log in&lt;/button&gt;

    【讨论】:

      猜你喜欢
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多