发布注册路径

时间:2021-03-21 05:18:09

标签: node.js reactjs

没有正确执行我的 handleSubmit 功能。将不胜感激任何输入。我想我很接近。我认为这就是它不起作用的原因。我只是想获得一个为注册页面工作的帖子请求。 State.username 或 password 似乎不起作用。我试过 this.state.username 并且它是未定义的。不知道我错过了什么。

import React, { useEffect, useState } from 'react';
import { TextField, Button, Typography, Paper } from '@material-ui/core';
import useStyles from './styles.css';
import { useDispatch } from 'react-redux';
import axios from 'axios';

const Auth = () => {

    const [username, setUsername] = useState('')
    const [password, setPassword] = useState('')

    const dispatch = useDispatch();

    const divStyle = {
        backgroundColor: 'white',
      };

     const handleSubmit = event => {
        event.preventDefault();
        const user = {
          username: state.username,
          password: state.password,

        }
        axios.post('http://localhost:5000/auth', { user })
          .then(res=>{
            console.log(res);
            console.log(res.data);
          })
      }

    return (
        <div style = {divStyle}>
            <form onSubmit={handleSubmit}>
            <h1>Registration</h1>
            <TextField 
                name='username' 
                variant='outlined' 
                label='username' 
                fullWidth 
                
                onChange={(e) => { 
                    setUsername( e.target.value)
                }}
             />
             <TextField 
                name='password' 
                variant='outlined' 
                label='password' 
                fullWidth 
                
                onChange={(e) => { 
                    setPassword( e.target.value)
                }}
             />
             <Button variant="container" color="primary" size="large" type="submit" fullwidth>Register</Button>
            </form>
        </div>
      );
}
 
export default Auth;

1 个答案:

答案 0 :(得分:1)

Sean,通过删除用户名和密码变量前面的“状态”来更改您的 handleSubmit 函数。

     const handleSubmit = event => {
        event.preventDefault();
        const user = {
          username: username,
          password: password,

        }
        axios.post('http://localhost:5000/auth', { user })
          .then(res=>{
            console.log(res);
            console.log(res.data);
          })
      }

您可能还需要在 <TextField> 组件上放置一个 value 属性。在这种情况下,您将执行 value={username}value={password}