为什么我第一次在React中单击提交时状态不会改变或无法工作

当您单击提交时,它表示成功,但应该失败,因为字段为空。第一次单击后,它可以完美运行。

提交按钮跳入handleSubmit函数,并且在第一次单击后可以正常工作。不知道我是否需要其他东西来确保它在第一次使用时能工作?

import React, { Component } from 'react';
import Avatar from '@material-ui/core/Avatar';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import TextField from '@material-ui/core/TextField';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import Link from '@material-ui/core/Link';
import Grid from '@material-ui/core/Grid';
import Box from '@material-ui/core/Box';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';
import { withStyles } from "@material-ui/core/styles";
import { Route, Redirect } from "react-router-dom";



import SuccessAlert from '../Components/SuccessAlert'
import { Alert, AlertTitle } from '@material-ui/lab';
import Snackbar from '@material-ui/core/Snackbar';
import MuiAlert from '@material-ui/lab/Alert';

const useStyles = theme => ({
  paper: {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'left',
  },
  avatar: {
    margin: theme.spacing(1),
    backgroundColor: theme.palette.secondary.main,
  },
  form: {
    width: '100%', // Fix IE 11 issue.
    marginTop: theme.spacing(1),
  },
  submit: {
    margin: theme.spacing(3, 0, 2),
    maxWidth: "200px"
  },
  root: {
    overFlowY: "scroll",
    marginTop: "8%",
    marginRight: "20px"
  },
  title: {
    fontSize: "20px",
    position: "absolute",
    left: "50px",
    marginRight: "50px"
  },
});


export class Connect extends Component {
  constructor(props) {
    super(props);
    this.state = { name: "", email: "", message: ""};
    this.state = { showAlert: false };
    this.state = { emptyName: false, emptyEmail: false, emptyMessage: false };
    this.state = { helpName: "", helpEmail: "", helpMessage: "" };
  }


  handleSumbit = (event) => {
    event.preventDefault();

    const formData = {
      name: this.state.name,
      email: this.state.email,
      message: this.state.message,
    };

    let errorCounter = 0;

    if (this.state.name == "")
    {
      this.setState({ emptyName: true, helpName: "Field must not be empty"})
      errorCounter = errorCounter + 1
    }
    else {
      this.setState({ emptyName: false, helpName: ""})
    }

    if (this.state.email == "")
    {
      this.setState({ emptyEmail: true, helpEmail: "Field must not be empty"})
      errorCounter = errorCounter + 1
    }
    else {
      this.setState({ emptyEmail: false, helpEmail: ""})
    }

    if (this.state.message == "")
    {
      this.setState({ emptyMessage: true, helpMessage: "Field must not be empty"})
      errorCounter = errorCounter + 1
    }
    else {
      this.setState({ emptyMessage: false, helpMessage: ""})
    }

    if (errorCounter != 0)
    {
      return false;
    }

    this.setState({ emptyMessage: false, emptyEmail: false, emptyName: false})
    this.setState({ showAlert: true });
    this.setState({ name: "", email: "", message: "" });

    //this.props.sendMessage(formData);

    setTimeout(function(){ this.setState({ showAlert: false }) }.bind(this), 5000);
  };

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

  render() {

    const SubmitButton = (props) => {
      return <Route render={props => <Redirect to="/home" />}/>
    }

    const { classes } = this.props;
    return (

      <div>
      <div className={classes.root}>
      <div className={classes.title}>
        <h1>Connect with me</h1>

      <div className={classes.paper}>
        <Typography component="h1" variant="h5" style={{maxWidth: "400px"}}>
          Say Hi! If you want to collaborate on something, or just want to connect with me, send me a message below.
        </Typography>
        <form className={classes.form} noValidate>
          <TextField
            error={this.state.emptyName}
            helperText={this.state.helpName}
            variant="outlined"
            margin="normal"
            required
            fullWidth
            name="name"
            label="Name"
            type="name"
            id="name"
            value={this.state.name}
            onChange={this.handleChange}
            style={{maxWidth: "500px"}}
          />

          <TextField
            error={this.state.emptyEmail}
            helperText={this.state.helpEmail}
            variant="outlined"
            margin="normal"
            required
            fullWidth
            id="email"
            label="Email Address"
            name="email"
            autoComplete="email"
            autoFocus
            value={this.state.email}
            onChange={this.handleChange}
            style={{maxWidth: "500px"}}
          />

          <TextField
            error={this.state.emptyMessage}
            helperText={this.state.helpMessage}
            variant="outlined"
            margin="normal"
            required
            fullWidth
            id="message"
            label="Message"
            rows="4"
            name="message"
            value={this.state.message}
            onChange={this.handleChange}
            autoComplete="none"
            autoFocus
            multiline
          />

          <Button
            type="submit"
            fullWidth
            variant="contained"
            color="primary"
            className={classes.submit}
            onClick={this.handleSumbit}
          >
            Send Message
          </Button>

        </form>
        {this.state.showAlert ? (
                <SuccessAlert/>
              ) : null}
      </div>


    </div>
      </div>
    </div>
    );
  }
}





export default withStyles(useStyles)(Connect);
评论
  • ad_est
    ad_est 回复

    Every time you do this.state in the constructor, the previous one is overriden.

       this.state = { name: "", email: "", message: ""};
        this.state = { showAlert: false };
        this.state = { emptyName: false, emptyEmail: false, emptyMessage: false };
        this.state = { helpName: "", helpEmail: "", helpMessage: "" };
    

    尝试

    this.state = { 
            name: "", email: "", message: "", 
            showAlert: false, emptyName: false, 
            emptyEmail: false, emptyMessage: false,  
            helpName: "", helpEmail: "", helpMessage: ""
    };
    

    单行或多行都可以,但是必须是一次分配。