首页 > 解决方案 > 在 ReactJS 的本地存储中获取空数据

问题描述

当我单击提交按钮时,我应该在本地存储中获取数据,但我的对象数组完全为空

我正在使用 titleDesMap 变量为 localArray 变量赋值,我正在获取数据但没有进入本地存储。

我的问题没有得到任何合适的答案。

任何人都可以请帮助...?

class Body extends React.Component {
  titleDescMap = new Map();
  localArray = new Array();
  constructor() {
    super();
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleChangeTitle = this.handleChangeTitle.bind(this);
    this.handleChangeDescription = this.handleChangeDescription.bind(this);
    this.handleCheckBoxChange = this.handleCheckBoxChange.bind(this);
  }

  state = {
    countTodo: 1,
    valueTitle: "",
    valueDescription: "",
    checkStatus: false,
    routeLoading: false,
    localStorageData: {},
  };

  statesStatus() {
    return {
      checkStatus: this.state.checkStatus,
    };
  }

  handleChangeTitle(event) {
    this.setState({
      valueTitle: event.target.value,
    });
  }

  handleChangeDescription(event) {
    this.setState({
      valueDescription: event.target.value,
    });
  }

  handleCheckBoxChange(event) {
    this.setState((prev) => ({ checkStatus: !prev.checkStatus }));
  }

  async handleSubmit(event) {
    event.preventDefault();
    this.setState({ routeLoading: true });

    var previousTitle = this.titleDescMap.has(this.state.valueTitle);

    // Sending data to database

    // Checking if any title and desc is previously stored
    if (previousTitle) {
      alert("Please Enter Another Title (which you have never used)");
    } else {
      // Setting the values in title and description into Map
      this.titleDescMap.set(this.state.valueTitle, this.state.valueDescription);

      // Updating id as counter increases 1
      const todoData = await axiosURL.get("/todo-data").then((res) => {
        this.setState({ routeLoading: true });
        return res.data;
      });
      this.setState({ routeLoading: false });
      this.setState({
        countTodo: todoData[todoData.length - 1].countTodo + 1,
      });

// Starts here

        this.localArray.push(this.titleDescMap);
        localStorage["localStorageData"] = JSON.stringify(this.localArray);
        console.log(JSON.parse(localStorage["localStorageData"]));
        console.log(this.localArray);

//Ends here

      }
    this.props.history.push("/submit");
  }

  render() {
    if (this.state.routeLoading) {
      return (
        <div className="spinner-design-outer">
          <SpinnerRoundOutlined
            className="spinner-design-inner"
            color="#337AB7"
            size="100px"
          />
        </div>
      );
    }
    return (
      <div className="body-container">
        <p className="body-direction">Fill To Save Your Todo</p>
        <form method="post" onSubmit={this.handleSubmit}>
          <div className="form-group">
            <label>Title</label>
            <input
              type="text"
              className="form-control"
              placeholder="Title here"
              value={this.state.valueTitle}
              onChange={this.handleChangeTitle}
            />
          </div>
          <div className="form-group">
            <label>Description</label>
            <br />
            <textarea
              className="form-control"
              placeholder="Description here"
              rows="4"
              cols="40"
              value={this.state.valueDescription}
              onChange={this.handleChangeDescription}
            />
          </div>
          <div className="form-check">
            <input
              type="checkbox"
              className="form-check-input"
              onChange={this.handleCheckBoxChange}
            />
            <label className="form-check-label body-input-label">
              Save Permanently
            </label>
          </div>
          <button type="submit" className="btn btn-primary">
            + Add
          </button>
        </form>
      </div>
    );
  }
}

export default withRouter(Body);

标签: javascriptreactjslocal-storagejsx

解决方案


本地存储不能像那样直接变异。它的行为更像 JS Map,带有getItemgetter 和setItemsetter:

// Change this
localStorage["localStorageData"] = JSON.stringify(this.localArray);

// to this
localStorage.setItem("localStorageData", JSON.stringify(this.localArray));

// log like that
console.log(JSON.parse(localStorage.getItem("localStorageData")));

参考:https ://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

编辑:

另一个问题是您试图序列化 ( JSON.stringify()) 包含Map数据结构的数组。似乎它不能以这种方式工作(JSON 不支持Maps - 它会将它们转换为空对象):您需要Map先将 转换为数组(请参阅https://2ality.com/2015/08/es6-地图-json.html):

// change this
this.localArray.push(event.this.titleDescMap);

// to this
this.localArray.push([...event.this.titleDescMap]);

当您从 a 获取数据时localStorage,您可能需要将此数组转换回 a Map


推荐阅读