我正在开发我的项目与reactjs和redux,所以我想显示不同的链接在导航栏时,我登录或注销。当我点击登录它的确定和一切工作正常,但当我点击注销它不改变导航栏automaticclly,我必须刷新页面。任何人可以帮助我吗?这里是我的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>
)
}
}
1条答案
按热度按时间lyfkaqu11#
您不能在注销时将accessToken设置为null。此accessToken是redux状态中的访问标记的引用。redux状态仍包含访问标记。
您必须创建
action
,并将redux中的accessToken设置为null,然后在注销时调用该函数。