reactjs - 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。感谢您的帮助!
解决方案
你想得到错误的方式不正确我建议你在 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)
})
}
..........
}
推荐阅读
- c - Us-100 超声波传感器:零结果
- python - Python Tkinter:一个滑块小部件可以控制另一个滑块小部件吗
- c - 如何在块的情况下解决 c 中 libyaml 中的别名事件
- sharepoint - SharePoint 列表 - 无法在查阅列中创建规则
- angular - Angular 12 项目的 UI 框架
- swiftui - 在 swiftUI 中绘制箭头
- merge - 将 PDF 与 Ghostscript 合并时,如何构建现有书签?
- java - 如何发送 HTTP POST 请求并在 android 上处理数据?
- html - 我怎样才能实现这个设计?
- django - Django 使用当前用户设置表单集