将对象数组保存到javascript localStorage无法正常工作

时间:2018-08-08 06:59:17

标签: javascript reactjs local-storage

我正在尝试在本地存储中存储对象数组。我正在使用this common method

localStorage.setItem( 'products', JSON.stringify(this.state.products) );
let initialProducts = JSON.parse(localStorage.getItem("products") || "[]")

我遇到了错误:

SyntaxError: Unexpected token o in JSON at position 1

我知道错误意味着我要两次解析JSON,但是如果不解析它,当我从localStorage获得“产品”时,它是:

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

我在做什么错了?

完整代码:

import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
import ProductList from "../products/ProductList";
import productData from "../products/model";

class App extends Component {
  constructor(props) {
    super(props);
    let initialProducts = JSON.parse(localStorage.getItem("products") || "[]")
    console.log(initialProducts);
    this.state = {
      newProductName: "",
      newProductPrice: 0,
      products: initialProducts
    };
  }

  updateNewProductName = event => {
    this.setState({ newProductName: event.target.value });
  };

  updateNewProductPrice = event => {
    this.setState({ newProductPrice: event.target.value });
  };

  addProduct = () => {
    this.state.products.push({
      name: this.state.newProductName,
      price: this.state.newProductPrice
    });
    this.setState({
      products: this.state.products
    });
    localStorage.setItem( 'products', JSON.stringify(this.state.products) );
  };

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <div className="App-header-container">
            <img
              src="https://www.ezyvet.com/wp-content/uploads/2016/04/ezyVet-Logo-22-4.png"
              alt="ezyVet Cloud Veterinary Practice Management Software"
              id="logo"
              className="App-logo"
              data-height-percentage="65"
              data-actual-width="768"
              data-actual-height="252"
            />
          </div>
        </header>
        <div className="App-header-container">
          <ProductList products={this.state.products} />
          <input
            type="text"
            id="uname"
            name="uname"
            required
            minLength="2"
            placeholder="name"
            value={this.state.newProductName}
            onChange={this.updateNewProductName}
          />
          <input
            type="number"
            id="uprice"
            name="uprice"
            required
            placeholder="price"
            value={this.state.newProductPrice}
            onChange={this.updateNewProductPrice}
          />
          <button onClick={this.addProduct}>Add Product</button>
        </div>
      </div>
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:0)

当我在JSON.parseJSON.stringify上加倍时,它可以工作。

例如:

let initialProducts = JSON.parse(JSON.parse(localStorage.getItem("products")));
localStorage.setItem( 'products', JSON.stringify(JSON.stringify(this.state.products) ));

可能与嵌套在数组内部的对象有关。