简体   繁体   中英

useState with a boolean

i have a react next.js project and a form. i want to use a slider in my form. by the way i use semantic ui react. i have one useState hook with the following input:

function CreateTicket() {
  const [ticket, setTicket] = useState({
    name: "",
    description: "",
    media: "",
    priority: false
  });
....

and an handleChange, handleSubmit and an handleToggle function. When i submit the form in my console.log it dont set the value of priority back to false.

      <Checkbox
        style={{ padding: "1rem" }}
        label="Important?"
        name="priority"
        toggle
        onChange={handleToggle}
      />

  const handleToggle = event => {
    let { priority } = event.target;
    setTicket(prevState => ({ ...prevState, priority: !priority }));
  };

console.log ->

after page refresh:

{name: "", description: "", media: "", priority: false}

after: toggle

{name: "", description: "", media: "", priority: true}

after a second toggle

{name: "", description: "", media: "", priority: true}

What do i wrong?

You need to destructure priority from prevState , not event.target :

const handleToggle = event => {
  setTicket(({ priority, ...prevState }) =>
    ({ ...prevState, priority: !priority })
  );
};

As an optimization, you can memoize handleToggle with useCallback() so that <Checkbox/> doesn't need to re-render every time your state updates:

const handleToggle = useCallback(event => {
  setTicket(({ priority, ...prevState }) =>
    ({ ...prevState, priority: !priority })
  );
}, [setTicket]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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