gpt4 book ai didi

reactjs - useState 在输入字段之外不工作(基于函数的 Reactjs)

转载 作者:行者123 更新时间:2023-12-04 04:06:41 26 4
gpt4 key购买 nike

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

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

最佳答案

你想要得到错误的方式不正确我建议你在 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)
})
}
..........
}

关于reactjs - useState 在输入字段之外不工作(基于函数的 Reactjs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62374139/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com