【问题标题】:Update single document by document ID - Firestore按文档 ID 更新单个文档 - Firestore
【发布时间】:2021-03-26 15:52:38
【问题描述】:

我正在尝试根据状态是“不喜欢”还是“喜欢”来设置喜欢和不喜欢的功能。单击喜欢的产品时,状态应该会更新。我似乎无法弄清楚如何将当前文档的 ID 传递给 .doc!

起始状态:

const [entities, setEntities] = useState([]);

这是我的不同功能(entity.id 显然给了我一个错误 - 未定义):

const unlikeProduct = async () => {

    firestore()
      .collection('likes')
      .doc(entity.id)
      .update({
        status: "unliked",
      })
      .then(() => {
          console.log("unliked");
        Alert.alert(
          'You have unliked this product!',
        );
      });
  };

向like函数发送调用的按钮:

<View style={styles.addToCartBtn}>
              <Icon name="heart" size={15} color={colours.white} onPress={() => unlikeProduct()}/>
            </View>

此功能显示所有状态为“喜欢”的产品:

    firestore()
      .collection('likes')
      .where('status', '==', 'liked')
      .onSnapshot(
        (querySnapshot) => {
          const newEntities = [];
          querySnapshot.forEach((doc) => {
            const entity = doc.data();
            entity.id = doc.id;
            newEntities.push(entity);
          });
          setEntities(newEntities);
        },
        (error) => {
          console.log(error);
        },
      );
  }, []);

tldr; 我只是想检索我想要区别的产品的文档 ID。

【问题讨论】:

    标签: javascript firebase react-native google-cloud-firestore


    【解决方案1】:

    假设您正在映射实体以显示视图,您可以访问每个实体的 id 并将其传递给您的 distinctProduct 函数。像这样的:

    {entities.map((entity) => (
      <View style={styles.addToCartBtn}>
        <Icon name="heart" size={15} color={colours.white} onPress={() => unlikeProduct(entity.id)}/>
      </View>
    ))}
    

    然后在您的 distinctProduct 函数中接收 entity.id 作为参数,它将不再是未定义的。像这样:

    const unlikeProduct = async (id) => {
    
    firestore()
      .collection('likes')
      .doc(id)
      .update({
        status: "unliked",
      })
      .then(() => {
          console.log("unliked");
        Alert.alert(
          'You have unliked this product!',
        );
      });
    };
    

    【讨论】:

    • 哦,非常感谢!由于某种原因,我没有想到 id 值。马上工作。 :))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 2019-06-29
    • 1970-01-01
    • 2020-04-19
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多