简体   繁体   中英

React: useState not preserving updated state upon click

Update: I was truly trying to reinvent the wheel here, the code below works if you use it in conjunction with React's Link or NavLink instead of anchor tags, it has built-in listening functionality that will keep track of the page you are currently on and pass along the updated state accordingly as your route changes to a different page.Thank you to everyone that chimed in and pointed me in the right direction!

I'm still fresh off the block with React, especially with hooks, but what I'm trying to accomplish is to trigger the 'active' tab class of my navbar elements through conditional rendering and managing state with useState. However, when I call 'setActiveTabIdx' upon click, I can't tell if it's not updating state at all, or if it is and is resetting to the default value upon re-render. I was trying to use my dev tools to monitor upon click but it's happening too fast for me to say one way or the other. I've messed around a fair bit at this point trying a number of different things if anyone would be willing to take a look, thanks!


const NavBar = () => {

  const [activeTabIdx, setActiveTabIdx] = useState(0)

  const navItems = ['About', 'Services', 'Oils', 'New Patients', 'Courses', 'Recommendations', 'Contact' ]

  const renderedItems = navItems.map((nav, idx) => {

    const active = idx === activeTabIdx ? 'active' : ''

    return (
    <a 
      onClick={() => setActiveTabIdx(idx)} 
      href={`${nav.split(' ').join('').toLowerCase()}`} 
      className={`${active} item`}
      key={idx}
      >{nav}</a>
    )
  })

  return (
    <div className="ui tabular menu">
      {renderedItems}
    </div>
  );
};

export default NavBar;

You are trying to change state (which is done) and then redirect user to other page (which is also done). The state resets after redirection.

It seems it is resetting, I added this block to check:

const NavBar = () => {

  const [activeTabIdx, setActiveTabIdx] = useState(0)

  const navItems = ['About', 'Services', 'Oils', 'New Patients', 'Courses', 'Recommendations', 'Contact' ]
  
  // --------- Start block --------- 

  useEffect(() => {
      console.log(`current state: ${activeTabIdx}`);
  }, [activeTabIdx]);

  // --------- End block --------- 

  const renderedItems = navItems.map((nav, idx) => {

    const active = idx === activeTabIdx ? 'active' : ''

    return (
    <a 
      onClick={() => setActiveTabIdx(idx)} 
      href={`${nav.split(' ').join('').toLowerCase()}`} 
      className={`${active} item`}
      key={idx}
      >{nav}</a>
    )
  })

  return (
    <div className="ui tabular menu">
      {renderedItems}
    </div>
  );
};

export default NavBar;

And to check codesandbox

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