Javascript 有没有办法防止相同的IF循环
嘿,伙计们,我正在检查我的应用程序版本,以清除缓存并删除本地存储。但有些地方不对劲,因为我处于一个循环中,应用程序一直在刷新。我做错了什么? 基本上,我正在我的Javascript 有没有办法防止相同的IF循环,javascript,reactjs,local-storage,Javascript,Reactjs,Local Storage,嘿,伙计们,我正在检查我的应用程序版本,以清除缓存并删除本地存储。但有些地方不对劲,因为我处于一个循环中,应用程序一直在刷新。我做错了什么? 基本上,我正在我的localStorage中创建一个currentVersion项,并请求检查是否有新版本。但是我的currentVersion不断更新,应用程序处于刷新循环中 export default class Login extends Component { constructor(props) { super(
localStorage
中创建一个currentVersion
项,并请求检查是否有新版本。但是我的currentVersion
不断更新,应用程序处于刷新循环中
export default class Login extends Component {
constructor(props) {
super(props);
currentVersion: '',
versionFromRequest: ''
}
}
async componentDidMount() {
axios.get(SERVER_URL + '/api/appVersion')
.then((response) => {
this.setState({
versionFromRequest: response.data
});
})
const branding = JSON.parse(localStorage.getItem('page'));
localStorage.setItem('currentVersion', branding.version)
this.setState({
branding,
pageReady: true,
currentVersion: branding.version
});
...
render() {
const { branding, versionFromRequest, currentVersion } = this.state;
if(currentVersion !== versionFromRequest){
caches.delete(arguments)
localStorage.removeItem('access')
window.location.reload()
} else {
return(
...
)
}
在我看来,问题似乎在于:
const branding=JSON.parse(localStorage.getItem('page')代码>
根据本地存储上的页面
键,您将获得currentBrandingVersion
此页面
键从未更新。因此,从它派生的currentVersion
,如果不匹配一次,将始终保持陈旧状态,页面将继续加载。要解决此问题,您可以执行以下操作:
if(currentVersion !== versionFromRequest){
...
window.location.reload();
localStorage.setItem('page', ...); //Set the key so that the condition doesn't match the next time.
} else {
...
}
您在哪里设置localStorage.setItem('page',…)
它来自上一个请求,是启动时执行的初始请求。它不基于此组件,因此它不存在;无法更新,因此将始终保持陈旧状态。不是吗?通常是的,这不会被更新到这个组件中。好吧,我理解,但为什么它让我进入同一个循环。我是说,如果currentVersion
不等于versionFromRequest
请执行其他操作,然后继续渲染。但它只让我进入这个if语句这是因为,currentVersion!==versionFromRequest
条件得到满足,您已经在其中编写了刷新页面的window.location.reload()
。当页面刷新时,此条件再次得到满足(请记住,您没有更新localStorage
中的page
键),并再次创建一个无限循环。@PandaMastr更新了答案。现在检查。但我无法将此项设置为本地存储,因为它是通过请求从我的App.js
上一个组件调用的,看起来像localStorage.setItem('page',JSON.stringify(response.data.branding))代码>所以它看起来像是一个设计缺陷。你明白问题所在吗?您正在比较旧版本和新版本,如果两者不匹配,则重新加载页面。但你永远不会用最新版本更新以前的版本。因此,页面不会一直在无限循环中重新加载自己。即使您是从App.js
进行设置,只要该组件在应用程序组件完成其部分后加载,也应该可以使用。你明白了吗?