如何使用 TypeScript 编辑 localStorage 中的值

How to edit a value in localStorage with TypeScript

我正在使用 Angular 开发一个简单的“绿灯、红灯”游戏,我正在使用 localStorage 存储玩家的分数和 maxScore。

我已经可以从存储在 localStorage 中的数组中读取每个 属性,但现在我只能在单击按钮后修改这些值。

这是我目前正在使用的测试数组:

[{"name":"test1","score":3,"maxScore":8},{"name":"test2","score":10,"maxScore":22}]

这个数组存储了一个名为“玩家”的键,所以它是一个玩家数组。

我的组件如下所示:

game.component.ts

export class GameComponentComponent implements OnInit {
  highScoreLS: number = this.getHighScoreData();
  scoreLS: number = this.getScoreData();

  highScore: number = 0;
  score: number = 0;
  state: string = 'RUN';

  faArrowRightFromBracket = faArrowRightFromBracket;
  faShoePrints = faShoePrints;

  constructor() {}

  ngOnInit(): void {}

  addPoint() {
    this.score++;
    if (this.score > this.highScore) {
      this.highScore = this.score;
    }
    this.changeHighScore();
    this.changeScore();
  }

  removePoint() {
    this.score--;
    if (this.score < 0) {
      this.score = 0;
    }
    this.changeHighScore();
    this.changeScore();
  }

  changeState() {
    if (this.state === 'RUN') {
      this.state = 'PAUSE';
    } else {
      this.state = 'RUN';
    }
  }

  getScoreData() {
    let localStorageItem = JSON.parse(localStorage.getItem('players') || '[]');
    let item = localStorageItem.find(
      (item: { name: string }) => item.name === 'test1'
    );
    let sc = item.score;
    return sc;
  }

  getHighScoreData() {
    let localStorageItem = JSON.parse(localStorage.getItem('players') || '[]');
    let item = localStorageItem.find(
      (item: { name: string }) => item.name === 'test1'
    );
    let hs = item.maxScore;
    return hs;
  }

  changeHighScore() {
    let localStorageItem = JSON.parse(localStorage.getItem('players') || '[]');
    let item = localStorageItem.find(
      (item: { name: string }) => item.name === 'test1'
    );
    item.maxScore = this.highScore;
    localStorage.setItem('players', JSON.stringify(item));
  }

  changeScore() {
    let localStorageItem = JSON.parse(localStorage.getItem('players') || '[]');
    let item = localStorageItem.find(
      (item: { name: string }) => item.name === 'test1'
    );
    item.score = this.score;
    localStorage.setItem('players', JSON.stringify(item));
  }
}

html 看起来像这样:

game.component.html

<div class="navbar navbar-dark bg-dark">
  <div class="container">
    <h2>Hi! </h2>
    <a class="navbar-brand" routerLink=""
      ><fa-icon [icon]="faArrowRightFromBracket"></fa-icon
    ></a>
  </div>
</div>

<div class="container flex vh-100">
  <div class="row m-3">
    <h3>HIGH SCORE: {{ highScoreLS }}</h3>
  </div>
  <div class="row m-3">
    <div class="card p-3">
      <h3>{{ state }}</h3>
    </div>
  </div>
  <div class="row m-3">
    <h3>SCORE: {{ scoreLS }}</h3>
  </div>
  <div class="row m-3">
    <div class="col">
      <button class="btn btn-outline-success" (click)="addPoint()">
        <fa-icon [icon]="faShoePrints"></fa-icon>
        Left
      </button>
      <button class="btn btn-outline-success" (click)="removePoint()">
        Right
        <fa-icon [icon]="faShoePrints"></fa-icon>
      </button>
    </div>
  </div>
</div>

问题是,当我点击按钮添加或删除一个点时,它删除了整个玩家数组,并创建了一个新的,如下所示:

{"name":"test1","score":0,"maxScore":1}

我已经使用 localStorage 工作了几天,所以我不知道我到底遗漏了什么或做错了什么。 我的想法是编辑这些值,scoremaxScore,但我不知道该怎么做。

编辑 我第一次点击添加点时,它只编辑了 maxScore,但是一次。下次我点击时,它给我这个错误:

ERROR TypeError: localStorageItem.find is not a function
    at GameComponentComponent.changeScore (game-component.component.ts:83:33)
    at GameComponentComponent.addPoint (game-component.component.ts:34:10)

您调用 localStorage.setItem 时仅使用单个项目而不是整个数组,因此您尝试的每个后续“发现”都将失败。

试试这个:

localStorage.setItem('players', JSON.stringify(localStorageItem));

尽管我不得不说,仅在那个组件中就有大量重复代码。你应该阅读一些关于数据结构和状态管理的文章。