3 回答
TA贡献1833条经验 获得超4个赞
我的情况是:
我有一个函数,与后端一起工作
function callApi() {
try {
} catch() {
clearToken(); // custom func for clearing tokens
// here I need to throw out the user when token is cleared
}
}
我想用“useEffect”钩子来扔掉
export function App () {
useEffect(() => {
if (!tokenFromLocalStorage) {
history.push('/login'); // react router history. url changing.
// I could not do this in the callApi func, because it would be
// neccessary to pass 'history' to the callApi as param on each calling
}
}, [tokenFromLocalStorage]);
return (<div></div>)
}
但问题是 useEffect 不会调用,因为本地存储更改不会重新呈现应用程序。
要解决此问题,请执行以下操作:
export function App () {
useEffect(() => {
if (!tokenFromLocalStorage) {
history.push('/login');
}
}, [tokenFromLocalStorage]);
return (<div></div>)
}
function callApi() {
try {
...
} catch() {
clearToken();
window.location.reload(); // throw out on the 'login' page if there are no tokens.
// forced reload needed because changing local storage
// does not rerender application
}
}
目前,useEffect将起作用,并将用户踢出。
TA贡献1818条经验 获得超3个赞
您可以在更改本地存储时调度操作。更好的方法是创建自定义钩子,这些钩子将完成工作或创建类似
function setLocalStorageItem(key,value) {
dispatch(...);
localStorage.setItem(key) = value;
}
function removeLocalStorageItem(key) {
dispatch(...);
localStorage.removeItem(key);
}
TA贡献1827条经验 获得超7个赞
您只需侦听对象上的存储事件:每当修改 localStorage 时,都会触发该事件。无需强制重新渲染,只需从事件中更新组件状态:windowstorage
const [isUserLoggedIn, setIsUserLoggedIn] = useState(localStorage.getItem('isUserLoggedIn'));
useEffect(() => {
const onStorage = () => {
setIsUserLoggedIn = localStorage.getItem('isUserLoggedIn');
};
window.addEventListener('storage', onStorage);
return () => {
window.removeEventListener('storage', onStorage);
};
}, []);
return (
<div>
{
isUserLoggedIn ?
<GlobalHeader
uniqueid="GlobalHeader"
signoutclickhandler={this.signOutHandler}
/>
:
<GlobalHeader
uniqueid="GlobalHeader"
signinclickhandler={this.signInHandler}
/>
}
</div>
)
添加回答
举报