简体   繁体   English

usestate 钩子在反应中不起作用

[英]the usestate hook is not working in react

Hello Guys This is how my code looks like大家好这是我的代码的样子

export default function Billing() {
    const classes = useStyles();
    const [balance, setBalance] = useState('0.00');
    const [upcoming, setUpcoming] = useState('0.00');
    const [lastmonth, setLastmonth] = useState('0.00');
    const [header, setHeader] = useState('Please Enter The Amount');
    const [open, setOpen] = useState(false);
    const [amountstate, setAmountstate] = useState(false);
    
    const [amounthelper, setAmounthelper] = useState('');
    const [sairam, setSairam] = useState(0);
    const onchange = async (e) => {
        console.log(sairam) 
        setSairam({amount: e.target.value})
    }
    const [modalchild, setModalchild] = useState(<>
    <form noValidate autoComplete="off">
       <TextField
            error={amountstate}
            type="number"
            value={sairam}
            onChange={onchange}
            label='Please enter the amount'
            helperText={amounthelper}
            variant="outlined"
        />
        <br />
        <br />
        <Button variant="contained" color="primary" onClick={() => addBalance()}>Add Balance</Button>
    </form>
    </>);
    const [country, setCountry] = useState(false);
    const [currency, setCurrency] = useState('');

 const addBalance = () => {
        console.log("Clicked :)")
        console.log(sairam) // outputs the inital value not the changed value

});
    return(<>
    <div className="balance-container">
        <div className="columns-top">
            <div className="column-top">
            <h1>${upcoming}</h1>
            </div>
            <div className="column-top">
            <h1>${balance}</h1>
            <Button variant="contained" color="primary" onClick={handleOpen}>Add Balance</Button>
            </div> 
            <div className="column-top">
            <h1>${lastmonth}</h1>
            </div>

        </div>
    </div>

    <Modal
        aria-labelledby="transition-modal-title"
        aria-describedby="transition-modal-description"
        className={classes.modal}
        open={open}
        onClose={handleClose}
        closeAfterTransition
        BackdropComponent={Backdrop}
        BackdropProps={{
          timeout: 500,
        }}
      >
        <Fade in={open}>
          <div className={classes.paper}>
            <h2 id="transition-modal-title">{header}</h2>
            
            {modalchild}
          </div>
        </Fade>
      </Modal>
     </>
    )
}

if I change the state sairam by using the function setSairam() the state is not getting updated and its only logging the initial state which is 0 i have even tried the loggint the event value of my input it works correct but the state alone is not changing please help me feel free to give me any other options if I change the state sairam by using the function setSairam() the state is not getting updated and its only logging the initial state which is 0 i have even tried the loggint the event value of my input it works correct but the state alone is not改变请帮助我随时给我任何其他选择

setSairam() is the asynchronous method so you can't get the updated value of sairam immediately after setSairam() . setSairam()是异步方法,因此您无法在setSairam()之后立即获取sairam的更新值。

const onchange = async (e) => {
    setSairam({amount: e.target.value})
    console.log(sairam) // This will console old value of sairam
}

You should use useEffect with adding a sairam dependency to check the updated state value.您应该使用useEffect添加sairam依赖项来检查更新的 state 值。

useEffect(() => {
   console.log(sairam) 
}, [sairam]);

IMPORTANT重要的

sairam will be the value of the TextField, so you should update the sairam to the string value, not object. sairam将是 TextField 的值,因此您应该将 sairam 更新为字符串值,而不是 object。

setSairam(e.target.value)

You will not get the updated value in your onChange function because that function is not aware when state is changed.您不会在onChange function 中获得更新的值,因为 function 不知道 state 何时更改。

Use useCallback to get the updated value of sairam .使用 useCallback 获取sairam的更新值。 Pass sairam in the dependency array.在依赖数组中传递sairam

const onchange = useCallback(async (e) => {
        console.log(sairam) 
        setSairam({amount: e.target.value})
    },[sairam]);

or use prevState或使用prevState

   setSairam(prevState => {
     console.log(sairam) 
    return ({amount: e.target.value})
  });

Another option is to pass sairam to onChange function.另一种选择是将sairam传递给 onChange function。 But I am not sure how it works since your markup is stored in state但我不确定它是如何工作的,因为您的标记存储在 state

onChange={(e)=>onchange(e, sairam)}


const onchange = async (e, sairam) => {
        console.log(sairam) 
        setSairam({amount: e.target.value})
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM