【问题标题】:localStorage not storing value as I want itlocalStorage 没有按我的意愿存储价值
【发布时间】:2019-10-10 03:57:24
【问题描述】:
import React, { Component } from "react";
import axios from 'axios';

class login extends Component {

  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: ''
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({ [event.target.id]: event.target.value });
  }

  handleSubmit(event) {
    axios.post('http://localhost:8080/validateAccount', {
      "username": this.state.username,
      "password": this.state.password
    })
      .then(function (response) {
        console.log(response.data)
        if(response === 'success') {
          localStorage.setItem('loggedin', 'true');
          console.log(response.data);
        }

      })
      .catch(function (error) {
        console.log(error);

      });
    event.preventDefault();
  }

  checkStorage() {
    console.log(localStorage.getItem('loggedin'))
  }


  render() {
    return (
      <div>
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input id="username" type="text" value={this.state.username} onChange={this.handleChange} /> <br></br>
        </label>

        <label>
          Password
          <input id="password" type="password" value={this.state.password} onChange={this.handleChange} /> <br></br>

        </label>
        <input type="submit" value="Submit" />

        <div id="typehere"></div>



      </form>
      <button onClick={this.checkStorage}>test</button>
      </div>


    );
  }
}

export default login;

我目前正在练习 react js,我正在尝试模仿 PHP $_SESSION['some-value'] 函数,它基本上保存会话值,直到您使用 session_destroy() 终止它(注销)。

我认为 localStorage 正是如此,但它没有保存它?上面是一个有效的登录表单,如果我输入了一个有效的用户名密码,那么它会到达 console.log("success") 并且 "loggedin" 在本地存储中设置为 true。现在,如果我使用“test”按钮,它将从本地存储中获取“loggin”并且应该返回 true,但它会返回 null。为什么?

我使用有效帐户登录并获得“成功”,然后立即进行快速测试并返回“null”。无论如何要得到我想要的?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    它失败的最可能原因是您的这部分代码:

    .then(function (response) {
        console.log(response.data)                  // <---  This indicates `response` is an object, not a string
        if(response === 'success') {                // <---  This expects `response` to be a string
          localStorage.setItem('loggedin', 'true');
          console.log(response.data);
        }
    
      })
    

    确保您检查了if (...) 中的正确项目。我猜你打算测试response.data === 'success' 而不是response === 'success'

    【讨论】:

    • 我刚刚意识到我有两个 console.logs 哎呀。这解决了它。经过进一步搜索,我也遇到了 sessionStorage ,我想知道有什么区别。对于登录,您通常应该有会话还是本地存储?
    • sessionStorage 仅在窗口打开时持续存在,并且只能由设置它的窗口访问。 @sssss 很高兴为您提供帮助
    【解决方案2】:

    尝试使用它,

    localStorage.setItem('loggedin', true);

    在获取值的同时 -> JSON.parse(localStorage.getItem("loggedin"))

    原因是,本地存储以字符串格式存储所有内容,即使您的布尔值也会保存为“真”、“假”,因此您需要检查字符串或使用 JSON.parse 再次将其转换为布尔值

    【讨论】:

    • OP 没有存储布尔值,也没有解释返回值null
    猜你喜欢
    • 1970-01-01
    • 2023-03-04
    • 2021-02-26
    • 2021-12-02
    • 1970-01-01
    • 2014-02-10
    • 2021-08-16
    • 1970-01-01
    • 2021-12-29
    相关资源
    最近更新 更多