简体   繁体   中英

how to change object value in react hooks?

I have a state with object {mode: 'light'} when the handleChange I click setMode to {mode: 'dark'} when the handleChange is clicked again it should return to {mode: 'light'} the flow is the same as toggling the hooks but Using an object, I tried it several times but it didn't work, how do I do it right?

this my state mode

 const [mode, setMode] = useState({
    mode: 'LIGHT'
  })

this my event

const handleChangeTheme = (e) => {
    setMode({
      ...mode,
      mode: 'DARK'
    })
  }

I throw the state to another component to display the state

<Navbar handleChangeTheme={handleChangeTheme} mode={mode.mode} />

this component navbar

 <li onClick={handleChangeTheme}>
    <span className='nav-item nav-link'>
        <b>{checked}</b>
     </span>
  </li>

when the handleChange is clicked it should look like true or false but this is an object

You can do like below. State change will reflect when object is assigned as new

const handleChangeTheme = (e) => {
  let newMode = Object.assign({}, mode);
  newMode.mode = mode.mode === "LIGHT" ? "DARK" : "LIGHT";
  setMode(newMode);
};

You don't actually toggle the mode, try using functional updates :

const toggleMode = () =>
  setMode((prev) => ({ ...prev, mode: !prev.mode }));

<li onClick={toggleMode}>...</li>;

If you change state as boolean it will simplify.

const [mode, setMode] = useState(true);

<Navbar
  handleChangeTheme={() => setMode(!mode)}
  mode={mode ? "LIGHT" : "DARK"}
/>;

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