如何解决在reactjs中注销后更改Navbar链接
我正在使用reactjs和redux开发项目,并且我想在登录或注销时在Navbar中显示不同的链接。因此,当我单击“登录”就可以了,并且一切正常,但是当我单击“注销”时,它不会自动更改导航栏,因此我必须刷新页面。有谁能够帮助我? 这是我的Navbar.js:
import React,{ useEffect,useState} from 'react'
import { usedispatch,useSelector } from 'react-redux';
import { Link,useHistory } from 'react-router-dom';
import { selectAccesstoken } from '../features/authentications/authenticationsSlice';
import axios from 'axios';
import './Navbar.css';
export const Navbar = (props) => {
const [loggedIn,setLoggedIn] = useState(false)
let accesstoken = useSelector(selectAccesstoken);
const [token,setToken] = useState(accesstoken)
const dispatch = usedispatch()
const [loggedOut,setLoggedOut] = useState([]);
const [errors,setErrors] = useState([]);
const logoUT_URL = 'http://127.0.0.1:8000/accounts_api/v1/dj-rest-auth/logout/';
const history = useHistory()
const removetokens = async () => {
try {
const response = await axios.post(`${logoUT_URL}`,{ headers: { "Authorization": `Bearer ${accesstoken}` }})
const data = response.data;
setLoggedOut(data)
console.log("data: ",data)
}
catch (err) {
console.log('err',err)
setErrors(err)
}
}
const handlelogout = async () => {
await logout();
history.push("login/");
};
const logout = () => {
removetokens()
localStorage.removeItem("access_token")
localStorage.removeItem("refresh_token")
console.log('localstrorage token after logout: ',localStorage.getItem("access_token"))
setLoggedIn(false);
accesstoken = null
console.log('accesstoken after logout:',accesstoken)
}
if (accesstoken) {
return (
<nav>
<ul className="menu">
<li className="logo"> My logo </li>
<li className="item">
<Link to="/">
articles
</Link>
</li>
<li>
<Link to="/topics">Topics</Link>
</li>
<li>
<Link to="/articles">Seconds</Link>
</li>
<li className="item">
<Link to="/management">
management
</Link>
</li>
<li className="item">
<Link to="/" onClick={handlelogout}>
logout
</Link>
</li>
</ul>
</nav>
)
} else if (!accesstoken) {
return (
<nav>
<ul className="menu">
<li className="logo"> My logo </li>
<li className="item">
<Link to="/">
articles
</Link>
</li>
<li>
<Link to="/topics">Topics</Link>
</li>
<li>
<Link to="/articles">Seconds</Link>
</li>
<li className="item">
<Link
to="/login"
onClick={() => {
localStorage.setItem("access_token",true);
setLoggedIn(true);
}
}
>
Login
</Link>
</li>
</ul>
</nav>
)
}
}
解决方法
您不能在注销内将accessToken设置为null。 该accessToken是您在redux状态下访问令牌的引用。您的redux状态仍然包含访问令牌。
accessToken = null
您必须在redux中将action
放置的accessToken创建为null。
然后在注销时调用该函数。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。