提交react中用户的注册表格



我想提交带有唯一名称的注册表格。

第一个问题:我似乎无法绘制第三次地图。错误显示数组不可迭代

第二个问题:我无法更改(数组不为空(部分中的setArray状态。我知道它是同步的,但我似乎找不到解决方案。

如果我想在更改setState后立即获得state值,请给我一个解决方案。我被这个问题困扰了三天。

import React from 'react';
import { Paper, Typography, TextField , Button, makeStyles} from '@material-ui/core';
import { Link} from 'react-router-dom'
import {useEffect} from 'react';
const useStyle = makeStyles((theme)=>(
{
formWrapper : {
display : 'flex',
width : '100%',
height : '100%',
alignItems : 'center',
justifyContent : 'center'
},
paper : {
padding : '20px',
margin : '20px'
},
textfield : {
marginLeft : '20px',
marginBottom : '10px'
},
span : {
margin: '10px',
marginLeft : '20px'
}
}
))
const Register = () =>{
const classes = useStyle();
const [name, setName] = React.useState('');
const [password, setPassword] = React.useState('');
const [array, setArray] = React.useState([])

const submit = (event) =>{
const obj = {}
event.preventDefault();
if(array.length === 0){ // Array is empty
if((name === null || password === null)||(name === '' || password === '')){ //check if name and password are empty
alert('Enter username and password')

}else{  // not empty then store in localstorage
localStorage.setItem('name', name);
localStorage.setItem('password',password);

obj.id = Math.random();
obj.name = localStorage.getItem('name');
obj.password = localStorage.getItem('password');
setArray(array.push(obj))
localStorage.setItem('array',JSON.stringify(array))
setName('');
setPassword('')
return alert('You are registered'); 

}
}
else  // array not empty
{
if((name === null || password === null) ||(name === '' || password === '')){
alert('Enter username and passsword');
}
let array2 = JSON.parse(localStorage.getItem('array')).map(user=> user.name)
var found = array2.includes(name);
if(found){
alert('User name Taken')
setName('')
setPassword('')
}
else{
localStorage.setItem('name', name);
localStorage.setItem('password',password);
obj.id = Math.random();
obj.name = localStorage.getItem('name');
obj.password = localStorage.getItem('password');
setArray([...array,obj])
localStorage.setItem('array',JSON.stringify(array))
console.log(array);
setName('');
setPassword('')
return alert('You are registered'); 
}

}
}
return(
<div>
<div className = {classes.formWrapper}>
<Paper elevation={3} className = {classes.paper} >
<Typography variant="h5" style = {{ textAlign : 'center'}}>Register</Typography>
<form noValidate autoComplete="off">
<TextField id="username" className={classes.textfield}  value = {name} name = "username"  label="Username" onChange = {e=>setName(e.target.value)} />
<br />
<TextField id="password" className={classes.textfield}  value = {password} name = "password"  label="Password" onChange = {e=>setPassword(e.target.value)} />
<br />
<span className ={classes.span}><Link to="/">Sign In</Link></span>
<br />
<Button variant="contained" color="secondary" style = {{width : '100%', marginTop : '10px'}} onClick = {submit} >Register </Button>
</form>
</Paper>
</div>
</div>

)
}

export default Register;

setArray(array.push(obj))是一个状态突变,array.push返回数组的新长度。向数组中添加一个元素,类似于在else分支中所做的操作。React状态更新是异步的,因此您不能等到状态更新后再将其持久化到本地存储。

const newArray = [...array, obj];
setArray(newArray);
localStorage.setItem('array', JSON.stringify(newArray));

或者,您可能只需要将状态更新排入队列,然后使用useEffect钩子在状态更新后进行持久化。

setArray([...array, obj]);
...
useEffect(() => {
localStorage.setItem('array', JSON.stringify(array));
}, [array]);

更新

由于您要将本地状态持久化到localStorage,因此您还需要从localStorage初始化本地状态。使用惰性状态初始值设定项函数从localStorage读取并返回初始状态值。

const [array, setArray] = React.useState(() => {
const initialState = localStorage.getItem('array');
return JSON.parse(initialState) || [];
});

如果JSON.parse(initialState)返回一个值,则这将是初始array状态值,否则,如果localStorage中没有存储任何内容,则null将是计算值,而|| []将返回一个空数组([](作为初始array状态值。

最新更新