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 .感谢您的帮助!

你想要得到错误的方式不正确,我建议你在 除了闭包

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)
})
}  
..........
}

最新更新