我想在註銷(清除會話)時更新我的NavBar。這是我寫的代碼:註銷更新NavBar React.js
App.js:
class App extends Component {
constructor(props){
super(props);
this.state = {};
}
componentWillMount(){
if(sessionStorage.getItem('access_token') != null && sessionStorage.getItem('id_token') != null){
this.setState({loggedIn: true});
}
}
render() {
return (
<BrowserRouter>
<div>
<title>Webshop</title>
<NavBar/>
<Switch>
{/*Routes need to be include in App.js otherwise root can't find the paths*/}
<Route exact path='/' component={Home}/>
<Route exact path='/categories' component={Categories}/>
<Route exact path='/login' component={Login}/>
<Route exact path='/register' component={Register}/>
{this.state.loggedIn == true ? <Route exact path='/logout' component={Logout}/> : null}
<Route render={function(){
return (<NotFound/>);
}}/>
</Switch>
<Footer/>
</div>
</BrowserRouter>
);
}
}
NavBar.js:
class NavBar extends Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.state = {
isOpen: false
};
}
componentWillMount(){
if(sessionStorage.getItem('access_token') != null && sessionStorage.getItem('id_token') != null){
this.setState({loggedIn: true});
}
else{
this.setState({loggedIn: false});
}
}
toggle() {
this.setState({
isOpen: !this.state.isOpen
});
}
render(){
return(
<div>
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css'/>
<Navbar color="faded" light expand="md">
<NavLink className='navbar-brand' exact to='/'>
<img src={logo} alt='Brand' width='35px' height='35px'/>
</NavLink>
<NavbarToggler onClick={this.toggle} />
<Collapse isOpen={this.state.isOpen} navbar>
<Nav className="mr-auto" navbar>
<NavItem>
<NavLink className='nav-link' exact to='/categories'>
Categories
</NavLink>
</NavItem>
</Nav>
<Nav className='mx-auto' navbar>
<Form inline>
<FormGroup>
<Input size='sm' type="text" name="search" placeholder="Search" />
</FormGroup>
<Button size='sm'><i className='fa fa-search'></i></Button>
</Form>
</Nav>
<Nav className="ml-auto" navbar>
<NavItem>
<NavLink className='nav-link' exact to='/cart'>
<i className='fa fa-shopping-cart'></i>
</NavLink>
</NavItem>
{(this.state.loggedIn) ?
<NavItem>
<NavLink className='nav-link' exact to='/profile'>
<i className='fa fa-user'></i>
</NavLink>
</NavItem>
: null }
{(this.state.loggedIn == true) ?
<NavItem>
<NavLink className='nav-link' exact to='/logout'>
<i className='fa fa-sign-out'></i>
</NavLink>
</NavItem>
:
<NavItem>
<NavLink className='nav-link' exact to='/login'>
<i className='fa fa-sign-in'></i>
</NavLink>
</NavItem>
}
</Nav>
</Collapse>
</Navbar>
</div>
);
}
}
Logout.js:
class Logout extends Component{
componentDidMount(){
sessionStorage.clear();
}
render(){
return(
<div>
Now loggedOut;
</div>
)
}
}
的代碼執行以下操作,登錄後它將session_tooken存儲在sessionStorage中的access_token & id_token。然後通過重定向到主頁更新NavBar,現在NavBar包含註銷按鈕,因爲狀態更新爲loggedIn。現在,當我註銷時,我清除了會話,以便不再提供id_token & access_token。這應該觸發狀態更新登錄爲false &重新渲染NavBar組件,但不知何故它不。 (當我刷新頁面NavBar確實更新)
任何人都可以幫我嗎?