如何将数据写回存储?

How to write data back to storage?

我有一个名为 changePlaceName 的方法,我知道它在工作,但是在我调用 getPlaces 查看更改后,我没有看到新的地名,而是看到了名称我创建了一个新地方。

这是changePlaceName

export function changePlaceName(placeId: u32, placeName: PlaceName): void {
  assert(placeId >= 0, 'Place ID must be >= 0');
  const place = Place.find(placeId);
  logging.log(place.name);  //gives "Galata Tower"
  place.name = placeName;
  logging.log(place.name);  // gives "New Galata Tower"
}

我需要以某种方式保存它,但我不知道该怎么做。

我也试过这种方法;

export function changePlaceName(placeId: u32, placeName: string): void {
    assert(placeId >= 0, 'Place ID must be >= 0');
    const place = Place.find(placeId);
    logging.log(place.name);
    place.name = placeName;
    let newPlace = storage.get<string>(placeName, 'new galata tower');
    storage.set<string>(placeName, newPlace);
    logging.log('New place is now: ' + newPlace);
}

现在我的视觉代码抱怨 storage.set

中的 newPlace

我该如何解决?

Place.find的代码是什么?我假设您正在使用持久地图。

Place.set吗?您需要将地点存储回用于查找它的同一密钥。

因为您正在使用某种 class 来管理“地点”的概念,所以为什么不在 class 到 save() 这个地点添加一个实例方法呢?改名了吗?

顺便说一下,如果您在这里也发布了 Place 的代码,将会有所帮助

我猜它看起来像这样?

!注意:这是未经测试的代码

@nearBindgen
class Place {
  private id: number | null
  private name: string

  static find (placeId: number): Place {
    // todo: add some validation for placeId here
    const place = places[placeId]
    place.id = placeId
    return place
  }

  // here is the instance method that can save this class
  save(): bool {
    places[this.id] = this
  } 
}

// a collection of places where placeId is the index
const places = new PersistentVector<Place>("p")