从本地存储中删除项目后出现未处理的拒绝错误。刷新对其进行修复

时间:2019-02-24 03:47:48

标签: javascript reactjs syntax-error local-storage

因此,我尝试在网站上放置一个注销按钮,并将用户的令牌存储在localstorage中,但是当单击注销按钮并将令牌从本地存储中删除后,该网站会立即重定向回登录页面,出现错误Unhandled Rejection (SyntaxError): Unexpected token u in JSON at position 0

每次注销只执行一次。如果刷新页面,页面加载就很好,但是显然没有人希望在他们的网站上出现这样的错误。

这样登录后,令牌将被存储:

async userLogin(e) {
    const { email, password } = this.state;
    const target = e.target.value
    try {
      let response = await fetch("<API URL removed for security reasons>", {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          email: email,
          password: password,
          uid: email
        })
      });
      let res = await response.text();
      if (response.status >= 200 && response.status < 300) {
        let accessToken = res;
        console.log(accessToken);
        localStorage.setItem("access_token", accessToken);
        this.setState({
          loginFailed: false,
          isFlipped: true,
        });
      } else {
        let error = res;
        this.setState({
          loginFailed: true
        });
        alert("Invalid login credentials");
        throw error;
      }
    } catch (error) {
      this.setState({
        error: error,
        loginFailed: true
      });
      console.log("error: " + error);

    }
  }

localStorage.setItem("access_token", accessToken);是令牌的存储位置。我使用localStorage.removeItem("access_token")删除了令牌,我也尝试使用localStorage.clear()删除了令牌,但是返回登录屏幕时,它给出了相同的错误。按下注销按钮时,我要做的就是删除令牌并重定向到登录屏幕,这并不复杂。

 const logOut = () => {
    localStorage.clear()
    console.log(localStorage)
    return <Redirect to="/login"/>
  }

当根页面解析本地存储以检查令牌时,将出现错误。这是错误消息的来源:

  componentWillMount() {
    const hasToken = JSON.parse(localStorage.access_token)
    if (hasToken.token_info.token !== null) {
      this.setState({
        authenticated: true
      })
    }   
  }

1 个答案:

答案 0 :(得分:1)

之所以发生这种情况,是因为localStorage.access_token返回了undefined,并且用undefined解析JSON.parse会引发错误。因此您可以检查为

const hasToken = localStorage.access_token ? JSON.parse(localStorage.access_token) : null