小编Vik*_*rMS的帖子

使用函数中的变量删除对象的键和值

嘿,我正在尝试从 Javascript 对象内的状态中删除键:值对。

当我在代码中对键名称进行硬编码时,它可以工作,但是当我尝试使用函数调用中的变量时,它不会执行任何操作。

有人可以帮我吗?

这是一个对象示例:

  toppingsSelected: {
     "Onion":"true",
     "Mushrooms":"true",
  }
Run Code Online (Sandbox Code Playgroud)

这有效,硬编码:

deleteTopping = toppingName => {

   const { Onion, ...withoutOnion } = toppingsSelected;
   console.log(withoutOnion); // Returns object without onion

  };
Run Code Online (Sandbox Code Playgroud)

这不起作用:

deleteTopping = toppingName => {


   const toppingName = "Onion"; // Variable gets passed in

   const { toppingName, ...withoutOnion } = toppingsSelected;
   console.log(withoutOnion); // Returns original object, no change made

  };
Run Code Online (Sandbox Code Playgroud)

所以我基本上是想从 React 状态中删除一个键,但我对 Javascript 还很陌生。

我怎样才能让Javascript知道toppingName是一个键?

javascript object ecmascript-6 reactjs

3
推荐指数
1
解决办法
2094
查看次数

ComponentWillUnmount 取消订阅 Firestore

我正在尝试使用 ComponentWillUnmount 停止侦听 Firebase Firestore 集合更改:

https://firebase.google.com/docs/firestore/query-data/listen#detach_a_listener

var unsubscribe = db.collection("cities")
    .onSnapshot(function (){
      // Respond to data
      // ...
    });

// Later ...

// Stop listening to changes
unsubscribe();
Run Code Online (Sandbox Code Playgroud)

但是,我无法访问此取消订阅();因为它是在 ComponentWillMount 中声明的,我需要在 ComponentWillUnmount 中使用它。

如何在 ComponentWillUnmount 中使用这个 unsubscribe()?如果我尝试将它保存在状态中,它会抛出一个错误,即取消订阅不是一个函数。

  constructor() {
    super();
    this.state = {
      notes: [],
      unsubscribe: null
    };
    this.getNotes = this.getNotes.bind(this);
  }

  componentDidMount(){
    this.getNotes();
  }

  componentWillUnmount(){
    var unsubscribe = this.props.unsubscribe;
    unsubscribe();
  }

  getNotes = () => {
    const db = this.props.firestore;
    const colRef = db.collection("users").doc(this.props.uid)
    .collection("notes");

    let notes = …
Run Code Online (Sandbox Code Playgroud)

firebase reactjs google-cloud-firestore

2
推荐指数
1
解决办法
2653
查看次数