反应onchange事件:this.setState()未设置状态?

时间:2019-02-15 06:20:22

标签: javascript reactjs forms onchange

当用户在用户名和密码字段中输入值时,我试图通过用户名和密码的this.setState()设置状态。我正在使用onChange事件类型

  

问题:状态没有改变。我在render()中记录了this.state.data.username。

import React, { Component } from "react";
import { Form, Button } from "react-bootstrap";
import { Link } from "react-router-dom";

var Joi = require("joi-browser");

class Login extends Component {
  state = {
    data: { username: "a", password: "b " },
    errors: {
      email: "ddsfds",
      password: "aaaa"
    }
  };

  schema = {
    username: Joi.string()
      .min(0)
      .required()
      .label("Username"),
    password: Joi.string()
      .required()
      .label("Password")
  };

  handleSubmit = event => {
    event.preventDefault();
    console.log("submited.", event.target);

    const { data } = this.state;

    const { err } = Joi.validate(data, this.schema);

    if (err) {
      console.log("error is true", err);
    } else {
      console.log("not true");
    }
  };

  handleEmailOnChange = event => {
    const inputUsername = event.target.value;
    console.log("input is...", inputUsername);

    this.setState({ username: inputUsername });
  };

  handlePassword = event => {
    const passwordInput = event.target.value;

    this.setState({ password: passwordInput });
  };

  render() {
    console.log("username ", this.state.data.username);
    return (
      <div id="form-wrapper">
        <Form>
          <Form.Group controlId="formBasicEmail">
            <h4>Sign In</h4>
            <Form.Control
              type="email"
              placeholder="Enter email"
              onChange={this.handleEmailOnChange}
            />
            {/* <span>{this.state.errors.username} </span> */}
          </Form.Group>

          <Form.Group controlId="formBasicPassword">
            <Form.Control
              type="password"
              placeholder="Password"
              onChange={this.handlePassword}
            />
          </Form.Group>

          <div id="register-wrapper">
            <Link to="/register" type="button" className="btn btn-warning">
              Register Account
            </Link>
            <Button
              variant="primary"
              className="m-2"
              type="submit"
              onClick={this.handleSubmit}
            >
              Submit
            </Button>
          </div>
        </Form>
      </div>
    );
  }
}

export default Login;

2 个答案:

答案 0 :(得分:1)

您没有正确更新状态或未正确使用状态。构造函数中的状态包含带有usernamepassword

的数据对象
 handleEmailOnChange = event => {
    const inputUsername = event.target.value;
    console.log("input is...", inputUsername);

    this.setState(prev => ({data: {...prev.data, username: inputUsername } }));
  };

  handlePassword = event => {
    const passwordInput = event.target.value;
    this.setState(prev => ({data: {...prev.data, password: passwordInput } }));
  };

答案 1 :(得分:0)

您要更改的状态是this.state.username,控制台要更改的状态是this.state.data.username

要将data设置为您的状态,请使用:

this.setState(prevState => ({
  data: {
    username: inputUsername,
    ...prevState.data
  }
})