【问题标题】:Local storage is getting updated only after refreshing the page, is there any way to update it immediately after the setItem call本地存储只有在刷新页面后才会更新,有没有办法在 setItem 调用后立即更新它
【发布时间】:2021-04-01 19:39:45
【问题描述】:

在用户身份验证页面中,我尝试使用从 API 调用中获取的响应令牌设置本地存储,然后导航到主页,我尝试在该主页显示配置文件详细信息,如果localstorage是有值的,虽然更新了本地存储,但是刷新首页后才能使用,所以想在进入首页前立即更新本地存储,这样就不需要了刷新,我没有使用 redux,所以任何人都可以在不使用 redux 的情况下帮助我。

提前致谢。

登录功能

login(event) {
fetch('api link', {
  method: 'post',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    username: this.state.username,
    password: this.state.password,
  }),
})
  .then((Response) => Response.json())
  .then((result) => {
    console.log('result is: ', result);
    if (result.message === null) {
      this.setState({ response: 'Invalid Username' });
    } else if (result.message === 'INVALID_CREDENTIALS') {
      this.setState({ response: 'Invalid Password' });
    } else if (result.message === 'USER_DISABLED') {
      this.setState({ response: 'Not verified' });
    } else {
      localStorage.setItem('ResetToken', result.token);
    }
  });

}

首页

{localStorage.getItem('ResetToken') ? (
        <IconButton
          aria-controls="simple-menu"
          aria-haspopup="true"
          color="inherit"
          onClick={handleClick}
        >
          <AccountCircleIcon />
        </IconButton>
      ) : null}

【问题讨论】:

  • 您需要使用 props 传递状态变量和 setState 函数。您的身份验证组件应更新应用范围内的 isLoggedIn 状态,并且您的主页应检查 useEffect 块内的 isLoggedIn 并相应地呈现。

标签: javascript reactjs


【解决方案1】:

将您的 localStorage.getItem('ResetToken') 放入 setstate 以使其具有反应性,例如

constructor(props) {
 super(props);
 this.state = {token: localStorage.getItem('ResetToken')};
 }

 componentDidUpdate() {
  this.setState({token:localStorage.getItem('ResetToken')})
}
{this.state.token && (
    <IconButton
      aria-controls="simple-menu"
      aria-haspopup="true"
      color="inherit"
      onClick={handleClick}
    >
      <AccountCircleIcon />
    </IconButton>
  }

如果没有令牌,则组件不会渲染,如果有令牌,则会渲染

【讨论】:

  • 它不工作,图标仍然出现在重新加载@Neezar 后
【解决方案2】:

我认为问题在于您的页面在本地存储更新之前呈现。我找到了一种简单的异步方式来设置和获取本地存储项。您可以将其用作辅助函数。

const asyncLocalStorage = {
    setItem: function (key, value) {
        return Promise.resolve().then(function () {
            localStorage.setItem(key, value);
        });
    },
    getItem: function (key) {
        return Promise.resolve().then(function () {
            return localStorage.getItem(key);
        });
    }
};

【讨论】:

    猜你喜欢
    • 2022-10-21
    • 1970-01-01
    • 2022-07-12
    • 1970-01-01
    • 2021-05-31
    • 2017-08-13
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多