更新数组变量的状态 [英] Update state of array variable

查看:32
本文介绍了更新数组变量的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想改变 setArray 的状态,但我不能改变它.console.log 显示空数组.其他州正在工作,但不是这个我也使用过 useEffect 但什么也没发生.请给我一个解决方案.

从'react'导入React;从'react-router-dom'导入{链接}从反应"导入 {useEffect};const 寄存器 = () =>{const 类 = useStyle();const [name, setName] = React.useState('');const [password, setPassword] = React.useState('');const [array, setArray] = React.useState([])const提交=(事件)=>{常量对象 = {}event.preventDefault();if(array.length === 0){localStorage.setItem('name', name);localStorage.setItem('密码',密码);localStorage.setItem('array',JSON.stringify(array))obj.id = Math.random();obj.name = localStorage.getItem('name');obj.password = localStorage.getItem('password');setArray(array => [...array,obj])控制台日志(数组);return alert('您已注册');}}返回(<div>

<纸张高度={3} className = {classes.paper} ><排版变体=h5"style = {{ textAlign : 'center'}}>Register</Typography><form noValidate autoComplete="off"><TextField id="用户名";className={classes.textfield} style={{width : '95%'}} value = {name} name = "username";标签=用户名"onChange = {e=>setName(e.target.value)}/><br/><TextField id="密码";className={classes.textfield} style={{width : '95%'}} value = {password} name = password";标签=密码"onChange = {e=>setPassword(e.target.value)}/><br/><br/><链接到='/'>登录</链接><按钮变体=包含"颜色=次要"style = {{width : '100%'}} onClick = {submit} >Register </Button></表单></纸>

)}导出默认注册;

解决方案

setState 是异步的.这意味着你不能在一行调用它并假设状态在下一行发生了变化.

来自 React 文档.

<块引用>

setState() 不会立即改变 this.state 而是创建一个挂起的状态转换.调用此方法后访问 this.state 可能会返回现有值.无法保证对 setState 调用的同步操作,并且可能会批量调用以提高性能.

I want to change the state of setArray but I cant change it. The console.log shows empty array. The other states are working but not this I've used useEffect too but nothing is happening. Kindly give me a solution.

import React from 'react';

import { Link} from 'react-router-dom'

import {useEffect} from 'react';

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){
          localStorage.setItem('name', name);
          localStorage.setItem('password',password);
          localStorage.setItem('array',JSON.stringify(array))
          obj.id = Math.random();
          obj.name = localStorage.getItem('name');
          obj.password = localStorage.getItem('password');
          setArray(array => [...array,obj])
          console.log(array);
          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} style={{width : '95%'}} value = {name} name = "username"  label="Username" onChange = {e=>setName(e.target.value)} />
                <br />
                <TextField id="password" className={classes.textfield} style={{width : '95%'}} value = {password} name = "password"  label="Password" onChange = {e=>setPassword(e.target.value)} />
                <br />
                <br />
                <Link to='/'>SignIn</Link>
                <Button variant="contained" color="secondary" style = {{width : '100%'}} onClick = {submit} >Register </Button>
            </form>
            </Paper>
        </div>
    </div>

  )
}

export default Register;

解决方案

setState is asynchronous. It means you can’t call it on one line and assume the state has changed on the next.

From React Docs.

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

这篇关于更新数组变量的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆