You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React登录页handleChange更新state值为undefined问题求助

Fixing Undefined State Values in Your React Login Component

Hey there! Let's get that undefined username/password issue sorted out—you're really close, just a small misstep in your handleChange method.

The Root Problem

Right now, your handleChange is trying to access event.target.uname and event.target.password, but those properties don't exist on the input element. The input elements have a name attribute that matches your state keys (uname and password), and you should use that to dynamically update the correct state field.

The Fix

Update your handleChange method to use the input's name attribute to target the right state property. This way, one method handles both inputs cleanly:

handleChange(event) {
  const { name, value } = event.target;
  this.setState({ [name]: value });
}

Bonus: Fix Minor Markup Issues

While we're at it, there are a couple of small markup inconsistencies that don't break functionality but are good to fix:

  • Input id values shouldn't have a leading # (change id="#uname" to id="uname" and id="#pass" to id="pass")
  • The form attribute on your labels should match the input's id (change form="#unamelabel" to form="uname" and form="#passlabel" to form="pass")

Full Modified Component Code

Here's your component with all the fixes applied:

export default class Login extends React.Component {
  constructor(props) {
    super(props);
    this.state = { uname: '', password: '' };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    const { name, value } = event.target;
    this.setState({ [name]: value });
  }

  handleSubmit(event) {
    alert('A username and password was submitted: ' + this.state.uname + ' ' + this.state.password);
    event.preventDefault();
    fetch('https://localhost:8080/login', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        uname: this.state.uname,
        password: this.state.password,
      })
    });
  }

  render() {
    return (
      <div>
        <Header titleName={"Login"}>
          <div className="container">
            <div className="card"/>
            <div className="card">
              <h1 className="title">Login</h1>
              <form onSubmit={this.handleSubmit}>
                <div className="input-container">
                  <input 
                    name="uname" 
                    type="text" 
                    value={this.state.uname} 
                    id="uname" 
                    required 
                    onChange={this.handleChange}
                  />
                  <label form="uname">Username</label>
                  <div className="bar"/>
                </div>
                <div className="input-container">
                  <input 
                    name="password" 
                    type="password" 
                    value={this.state.password} 
                    id="pass" 
                    required 
                    onChange={this.handleChange}
                  />
                  <label form="pass">Password</label>
                  <div className="bar"/>
                </div>
                <div className="button-container">
                  <button type="submit"><span>Go</span></button>
                </div>
                <div className="footer"><a href="#">Forgot your password?</a></div>
              </form>
            </div>
          </div>
        </Header>
        <Footer/>
      </div>
    );
  }
}

Why This Works

By destructuring name and value from the input element, we use the input's name (which matches your state keys) to dynamically update the corresponding state property. This pattern is scalable too—if you add more form fields later, you won't need to write a new handler.

Now when you type into the inputs, your state will update correctly, and submitting the form will show the actual values instead of undefined!

内容的提问来源于stack exchange,提问作者Joss MT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:53:52