简体   繁体   中英

React hook useState not updating onclick

I am trying to update the sidebar class when the closehandler function is called but the state is not updating. How do I go about that.

function RiderSidebar({ sidebar, close }) {

const [SidebarClass, setSidebarClass] = useState('sidebar')

const closeHandler = (e) => {

    e.preventDefault();
    console.log("closed click");
    setSidebarClass("user-side-bar close")
    console.log("slidebar is " + SidebarClass);

    setTimeout(() => {
        close()
    }, 1000)
}
return (
    <div className={SidebarClass} >
        <button className="close-btn" onClick={closeHandler}>X</button>

        <ul>
            <li><NavLink to='/rider/dashboard' className="user-nav"  ><DashboardIcon />  Dashboard</NavLink></li>
            <li><NavLink to='/rider/orders' className="user-nav"  ><HistoryIcon /> Orders</NavLink></li>
            <li><NavLink to='/user/logout' className="user-nav"  ><PowerSettingsNewIcon /> Logout</NavLink></li>
        </ul>
    </div >
)
}

React batches the state update. If you will check the state update immediately after updating the state react then you may not get the updated state. You can check the updated state in render method. It should be updated there.

useState hook is asynchronous, and will not be reflected immediately.. try this:

  useEffect(() => {
    
    }, [SidebarClass]);

I think you add useEffect hooks to check I explain briefly what did you wrong when you click your close button closed handler function trigger and setState function calling at the same time( asynchronous ) console.log statement printed. //'side bar'

in your code, you can't verify your state change or not (only you can verify from the render method) because the closed handler function triggers only one time if you want to check your className is changed or not from console.log statement you must need useEffect hook it will trigger every time after your state changed so can conform it your className is changed or not

//only trigger one time 
 useEffect(()=>{
 console.log(SidebarClass);//output 'sidebar'
 },[])
        
 //hooks trigger every time after your state changed
  useEffect(()=>{
 console.log(SidebarClass); 
 //output 'sidebar' 
 //output user-side-bar close
            })
        
 //only trigger if SidebarClass state changed
 useEffect(()=>{
 console.log(SidebarClass);
 //output 'sidebar' 
 //output user-side-bar close
 },[SidebarClass]);

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