Почему мое состояние не меняется или не работает с первого раза, когда я нажимаю "Отправить" в React - PullRequest
0 голосов
/ 24 апреля 2020

Когда вы нажимаете кнопку «Отправить», появляется сообщение «Успешно», если сбой происходит, поскольку поля пусты. После первого щелчка он работает отлично.

Кнопка отправки переходит в функцию 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);

1 Ответ

1 голос
/ 24 апреля 2020

Каждый раз, когда вы делаете this.state в конструкторе, предыдущий переопределяется.

   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: ""
};

Одной или несколькими строками все в порядке, но оно имеет быть одним назначением.

...