Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

reactjs - useState Hook not updating properly

my useState hook is not updating properly, it is not able to take 2 values at a time ex:- my useState hook is

const [error, setError] = useState({
    empty: "",
    length: "",
  });

 const submitHandler = (e) => {
    e.preventDefault();
    if (email == "" || password == "")
      setError({ ...error, length: "no lengthy values" });
    if (email.length < 3) {
      setError({ ...error, empty: "no empty values" });
    }

setError updates only one out of 2 condition, same happened with useState array too, useState unable to update/push multiple data at a time , any answers would be highly appreciatable. Thank You

question from:https://stackoverflow.com/questions/65896518/usestate-hook-not-updating-properly

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

While you could use a callback instead, eg:

setError(error => ({ ...error, empty: "no empty values" }));

I think setting the state once would make a bit more sense. If a test doesn't generate an error, set the associated property to the empty string:

setError({
  length: email === "" || password === "" ? 'no lengthy values' : '',
  empty: email.length < 3 ? 'no empty values' : ''
});

Even better, separate out the different states:

const [emptyError, setEmptyError] = useState('');

and then, eg, call setEmptyError instead when you need to set the error for empty.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...