【问题标题】:The React Application does not work as intended when submitting a form提交表单时,React 应用程序无法按预期工作
【发布时间】:2021-06-08 03:35:50
【问题描述】:

我使用 React 为我的 Web 应用程序创建了一个注册页面。这是我的注册组件代码-

import React, { useState } from 'react';
import { Avatar,  Button, Paper, Grid, Typography, Container } from '@material-ui/core';
import axios from "axios";
import useStyles from './styles';
import Input from './Input';


const initialState = { name: '', email: '', password: '', mobile: '', confirmPassword: '' };

const Register = () => {
  const [form, setForm] = useState(initialState);
  const classes = useStyles();
  const handleSubmit = async () => {
      const { data } = await axios.post('http://localhost:4000/users/register', initialState);
      console.log(data); 
  };
  const handleChange = (e) => setForm({ ...form, [e.target.name]: e.target.value });
  return (
    <div>
      <Container component="main" maxWidth="xs">
        <Paper className={classes.paper} elevation={3}>
          <Typography component="h1" variant="h5">Sign up</Typography>
          <form className={classes.form} onSubmit={handleSubmit}>
            <Grid container spacing={2}>
                <Input name="name" label="Full Name" handleChange={handleChange} autoFocus/>
                <Input name="mobile" label="Mobile Number" handleChange={handleChange}/>
                <Input name="email" label="Email Address" handleChange={handleChange} type="email"/>
                <Input name="password" label="Password" handleChange={handleChange} type='password'/>
                <Input name="confirmPassword" label="Confirm Password" handleChange={handleChange} type="password"/>
            </Grid>
            <Button type="submit" fullWidth variant="contained" color="primary" className={classes.submit}>
              Sign Up
            </Button>
          </form>
        </Paper>
      </Container>
    </div>
  );
};
export default Register;

提交表单时,服务器端不会发出任何请求。相反,它再次重定向到同一页面,查询参数等于表单的输入正文。我在这里做错了什么?

【问题讨论】:

  • 网络标签中是否有任何请求发出?
  • 您的客户端和服务器运行在哪些端口上?
  • @RichardHpa 客户端在 3000 端口上运行,服务器在 4000 上运行。
  • @djolf 请求在服务器端发送,但页面在表单提交时重新呈现

标签: reactjs axios react-hooks


【解决方案1】:

您没有阻止表单的默认操作。由于您使用的是标准 html 表单,因此提交它只会默认为一个 get 请求,该请求将包含您所说的 url 中的值。

防止默认将允许您执行非默认操作,例如您想要的 axios 调用。

  const handleSubmit = async (e) => {
      e.preventDefault()
      const { data } = await axios.post('http://localhost:4000/users/register', initialState);
      console.log(data); 
  };

【讨论】:

    【解决方案2】:

    在handelSubmit 中使用event.preventDefault(),因为它会停止浏览器在提交表单时重新加载的默认操作。

    const handleSubmit = async (event) => {
          event.preventDefault();
          // other line of code
    };
    

    【讨论】:

    • 这与我已经发布的答案相同。仔细检查以确保尚未给出相同的答案。其他人可能会对您的答案投反对票。
    猜你喜欢
    • 2019-09-24
    • 2021-04-16
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多