首页 > 解决方案 > 如何在 cache.readQuery 或 cache.writeQuery 中使用 this.state.rent 值而不是 this.props.house.rent 值

问题描述

旧值返回输入字段。

我已经用输入字段值 this.state.rent (用户输入的值)初始化了 this.props.house.rent (这是返回的旧值),但我不能这样做,因为它变成了反模式语法,你可以在下面看到它代码注释。

cacheUpdate = (cache, { data: { updateHouse } }) => {
    const data = cache.readQuery({
      query: QUERY_CONFIRM_QUERY,
      variables: { id: this.props.confirmId },
    });
    const houses = data.queryConfirm.houses;
    const prevHouse = this.props.house;
    //prevHouse.rent = this.state.rent; // this.state.rent is user entered input value
    const updatedHouses = houses.map(house => {
      if (house.id === prevHouse.id) {
        const updatedHouseItem = _.pickBy(updateHouse, _.identity);
        return { ...prevHouse, ...updatedHouseItem };
      }
      return house;
    });
    data.queryConfirm.houses = updatedHouses;

    cache.writeQuery({
      query: QUERY_CONFIRM_QUERY,
      variables: {
        id: this.props.confirmId,
      },
      data,
    });
  };

我希望从缓存的 readQuery 或 writeQuery 中删除旧值。

标签: reactjsgraphqlapolloreact-apolloapollo-client

解决方案


希望这可以帮助某人。Ooof..我想了很多,实际上很简单。我想进行回调,但由于值来自数据库,所以不可能。无论如何,总而言之,简单地查看控制台中 data.queryConfirm.houses 的值并分配所需的数组,比如我需要的是 data.queryContact.houses[0].rent 并将其初始化为 this.state.rent。就这样。


推荐阅读