首页 > 解决方案 > Why isn't this spread operator updating my state properly?

问题描述

Basically, I'm checking if the user inputted an email or a phone number, and if they didn't I'm trying to change the state of "error". To make things simple, I omitted the "if (!user.email)"/ "if (!user.phone)" statement, even without it the code below doesn't work properly. I can't figure out why.

It will ONLY change the value of the first thing. If I console.log(error) after this code runs, I'll see {phone: true, email: false}. When I switch the order of the setError statements, I'd see {phone: false, email: true}.

  const [error, setError] = useState({
    email: false,
    phone: false,
  });
  
  const handleSubmit = (e) => {
    e.preventDefault();

    setError({ ...error, phone: true });
    setError({ ...error, email: true });
    
    }

标签: javascriptreactjsnext.jsstate

解决方案


推荐阅读