简体   繁体   中英

React js useEffect not updating useState value on location pathname change?

Reactjs useEffect not updating useState value on location pathname change.I have two clientLayout and AdminLayout I switch client to admin layout on the base of useState which is not update on change route or location path.It's multi layout concept.

import ClientLayout from './views/client-views/client-layout/index.js';
import AdminLayout from './views/admin-views/admin-layout/index';
import Layout from './views/layouts/Layout';
import {BrowserRouter as Router,useLocation} from 'react-router-dom';
import React,{useState,useEffect} from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';

function App() {

      const[clientLayout,setClientLayout] = useState(false);
      const location = useLocation();
      useEffect(()=>{
         let location = window.location.pathname;
         let pathname = location.split('/');
         if(pathname[1] == 'client'){
           setClientLayout(true)
       }
     },[window.location.pathname])


  return (
    <div className="App">
       <Router>
     {
       clientLayout ? <AdminLayout /> : <ClientLayout />
     }
       
       </Router>
      
    </div>
  );
}

export default App;

Try using location instead of window.location:

const location = useLocation();
useEffect(() => {
  let pathname = location.pathname.split("/");
  if (pathname[1] == "client") {
    setClientLayout(true);
  }
}, [location.pathname]);

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