首页 > 解决方案 > useState 在输入字段之外不起作用(基于函数的 Reactjs)

问题描述

我在我的网站上使用有状态变量作为注册组件。我将用户名和密码发送到我的服务器,然后返回一个用户 ID 号。如果出现错误,我会尝试将 errorMsg 状态变量设置为等于返回的错误消息。useState 适用于更改输入字段中的值,但不适用于我的应用程序的其他部分。它也不适用于作为道具传递的有状态变量。这是我的代码。

import React from 'react';
import {useState} from 'react';
import { Link, Redirect } from 'react-router-dom';
import bcrypt from 'bcryptjs';
import axios from 'axios';


export default function Signup(props) {

    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [password2, setPassword2] = useState('');
    const [openModal, setOpenModal] = useState(false);
    const [errorMsg, setErrorMsg] = useState('');
    let isAvailable = '';
    let id = null;
    let test = [];
    let axiosError = '';

    async function submitAccount() {
        const salt = bcrypt.genSaltSync(10);
        const hash = bcrypt.hashSync(password, salt)
        if (bcrypt.compareSync(password2, hash)) {

            await axios.post('http://localhost:5000/players/signup', {
            username: username,
            password: password})
            .then(res => {id = res.data; console.log(id)})
            .catch (err => {axiosError = err; console.log(axiosError)})

            if (axiosError != '') {
                axiosError = ''
                setErrorMsg('This username is taken. Try another')
                setUsername('')
                setPassword('')
                setPassword2('')
                setOpenModal(true)
                console.log(errorMsg)
                console.log(openModal)
            }

            else {
                console.log(id)  
            }
        }
    }    

    const handleClose = () => {
        setOpenModal(false);
    };

    return (
        <div>
            <form>
            <input type="text" label='username'
                onChange={e => setUsername(e.target.value)}
            />
            <input type="text" 
                onChange={e => setPassword(e.target.value)}
            />
            <input type="text"
                onChange={e => setPassword2(e.target.value)}/>
            </form>
            <button onClick={submitAccount}>Confirm</button>
            <p>The results are{props.cookies}</p>
        </div>

    )

}

这也是我的代码沙箱:https: //codesandbox.io/s/epic-lalande-v1nl3?file=/src/App.js。感谢您的帮助!

标签: reactjsjsx

解决方案


你想得到错误的方式不正确我建议你在 except 闭包中这样做

            await axios.post('http://localhost:5000/players/signup', {
            username: username,
            password: password})
            .then(res => {id = res.data; console.log(id)})
            .catch (err => {
                // axiosError = ''
                setErrorMsg('This username is taken. Try another')
                setUsername('')
                setPassword('')
                setPassword2('')
                setOpenModal(true)
                console.log(errorMsg)
                console.log(openModal)
            })
        }  
    ..........
}

推荐阅读