简体   繁体   English

无法从Firebase函数中获取setState

[英]can't get setState inside a firebase function out of it

first i set listaa as a global variable 首先,我将listaa设置为全局变量
i'm trying to take out the variable(array) "listaa" from the firebase function that sets it... I'm plannig to use it later to make some maths. 我试图从设置它的firebase函数中取出变量(数组)“ listaa” ...我打算稍后使用它进行一些数学运算。 I used console.log(listaa) inside the firebase function and it worked, but then when i try to use it() outside(the firebase function) it doens't work. 我在console.log(listaa)函数内部使用了console.log(listaa) ,它起作用了,但是当我尝试在firebase函数之外使用它()时,它就不起作用了。 I tried to use setState to make it usable outside but didnt work too 我试图使用setState使它在外部可用,但也没用

if (funcionar == 0) {
        //============================================================== ANTES ===================================================
        var newRef = firebase
          .database()
          .ref()
          .child("TransferenciasPraVendedores/")
          .push({
            vendedor: vend,
            dia: functions.dataHoje(),
            hora: functions.horaHoje()
          });


        var fire = database.ref("EstoqueCadaVendedor/" + vend);
        fire.once("value", snap => {
          items = [];
          snap.forEach(data => {
            items.push({
              key: data.key,
              data: data.val()
            });
          });
          console.log("items:");
          console.log(items);

          for (j = 0; j < prod.length; j++) {
            // var a = parseInt(snap.val().quantidade);
            console.log("d: " + items[j].data);
            listaa.push(items[j].data);
          }
          // this.setState({ lista:listaa })
          // console.log("lista:");
          // console.log(this.state.lista[2]);
          console.log("listaa");
          console.log(listaa);
        });
        console.log("listaaaaaaaaaaaaaa");
        console.log(listaa);

Ill use 'listaa' here: 我在这里使用'listaa':

        for (i = 0; i < prod.length; i++) {
          firebase
            .database()
            .ref()
            .child("EstoqueCadaVendedor/" + vend + "/")
            .update({
              [prod[i].key]: parseInt(quantNova[i]) + listaa[i]
            });
        }

        // this.setState({ quantidade: [], vendedor: "" });
      }

Did you review the order of the log messages ? 您是否查看了日志消息的顺序? if you look carefully, you will recognize the data gets available after later in the process. 如果仔细看,您将认识到该数据将在以后的过程中获得。 You probably need to use async/promise to wait until the data gets available or you can use a call back function 您可能需要使用异步/承诺来等待数据可用,或者可以使用回调函数

async 异步的

function to make sure the data is available in the list before you use it. 函数以确保在使用数据之前列表中的数据可用。

An async function can contain an await expression, that pauses the execution of the function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value. 异步函数可以包含await表达式,该表达式暂停函数的执行并等待传递的Promise的分辨率,然后恢复异步函数的执行并返回解析的值。

In the example below, I am passing a call back function that gets called when data is available : 在下面的示例中,我传递了一个回调函数,该函数在有数据时被调用:

  export function listReleases(callback) {
  //console.log("hello from list releases ");
  releasesRef.once("value").then(
    function(snapshot) {
      const releases = snapshot.val();
      if (releases) {
        callback("releases", releases);
      }
    },
    function(error) {
      // The Promise was rejected.
      console.error(error);
    }
  );
}

+++++++++++++++++++++++++++


 //call the function to get the data and pass a call back function 
 releases = listReleases(this.myCallback);


 myCallback = (key, value) => {
   //do whatever you need to do in here 
 };

Tuan over here. 团在这里。

  • The reason why you don't see it is because your code is asynchronous, so when you print console.log() at the end. 之所以看不到它,是因为您的代码是异步的,因此在最后打印console.log()时。 The firebase calls haven't finished yet.This is a typical race condition scenario. Firebase调用尚未结束。这是典型的竞争情况。
  • FYI, I personally prefer to use the promise style rathen than the callback, I think it makes the code cleaner and easier to read. 仅供参考,我个人更喜欢使用promise样式的rathen而不是回调,我认为它使代码更简洁,更易于阅读。 Try this: 尝试这个:

    let firebaseDB = firebase.database(); 让firebaseDB = firebase.database();

    if (funcionar == 0) { if(funcionar == 0){

     return firebaseDB.ref("TransferenciasPraVendedores/") .push({ vendedor: vend, dia: functions.dataHoje(), hora: functions.horaHoje() }) .then(() => { return firebaseDB.ref("EstoqueCadaVendedor/" + vend).once('value'); .then(snapshot => { let snap = snapshot.val(); items = []; snap.forEach(data => { items.push({ key: data.key, data: data.val() }); }); return {snap, items}; }) .then({snap, items} => { for (j = 0; j < prod.length; j++) { listaa.push(items[j].data); } //console.log(lista)// NOW your lista should have all the items // I would dispatch your redux action here. }) .catch(error => { throw error } 

Let me know if it helped. 让我知道是否有帮助。 I can look into it more in depth. 我可以更深入地研究它。 Saludos :) 礼炮:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM