Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 数组设置状态并获取数组响应本机_Javascript_Firebase_React Native_Google Cloud Firestore - Fatal编程技术网

Javascript 数组设置状态并获取数组响应本机

Javascript 数组设置状态并获取数组响应本机,javascript,firebase,react-native,google-cloud-firestore,Javascript,Firebase,React Native,Google Cloud Firestore,我试图将数组设置为状态,但它似乎没有设置。 我已经在下面发布了我的一些代码 我想做的是,用户可以将一个项目上传到firestore上的主集合,然后该项目将显示在主屏幕上的主列表上 我还希望用户能够通过点击他们自己的个人资料查看他们自己的项目,他们可以看到只有这些项目的列表 我采取的方法是将项目上载到firestore上的主集合,然后将文档id和集合引用(即“c”)都放入名为userItems的子集合中的文档中,该子集合位于该特定用户的文档中。我认为这是最好的方法,所以我只有“1个真实来源”,不必

我试图将数组设置为状态,但它似乎没有设置。 我已经在下面发布了我的一些代码

我想做的是,用户可以将一个项目上传到firestore上的主集合,然后该项目将显示在主屏幕上的主列表上

我还希望用户能够通过点击他们自己的个人资料查看他们自己的项目,他们可以看到只有这些项目的列表

我采取的方法是将项目上载到firestore上的主集合,然后将文档id和集合引用(即“c”)都放入名为userItems的子集合中的文档中,该子集合位于该特定用户的文档中。我认为这是最好的方法,所以我只有“1个真实来源”,不必担心重复,特别是如果我将来必须更新任何文档

正如我在顶部所说的,我的问题是,一旦我尝试在第二个方法“queryUserItems”中迭代数组,它就是空的。如果有人能够指出我做错了什么,我会非常感激,或者如果有人能够指出一种更优雅、更有效的方式来说明我最终要做的事情,那就是: 保存项目时,可以从主列表以及用户自己的列表中查看项目,这有点像Instagram的工作原理

谢谢您的帮助:)

UserProfile.js

constructor() {
    super();

    this.getUserItems = this.getUserItems.bind(this);


    this.state = {
        Name: '',
        Location: '',
        items: [],
        Keys: [],
        test: ''
    };
}

componentDidMount() {
    console.log('UserProfile');

    this.getUserItems();
    //this.queryKeys();

}


getUserItems = () => {

    const Keys = [];

    const userCollectionRef = firebase.firestore()
        .collection('a').doc('b')
        .collection('c')




    userCollectionRef.get()
        .then((querySnapshot) => {
            console.log("user doc received");

            querySnapshot.forEach(function (doc) {

                console.log('Doc.id: ', doc.id);
                console.log('Doc.Key: ', doc.data().Key);
                console.log('Doc.CollectionRef: ', doc.data().CollectionRef);

                const {Key, CollectionRef} = doc.data();

                Keys.push({
                    Key,
                    CollectionRef
                })

            }); // foreach loop end
this.queryKeys(keys);




        }).catch(function (error) {
        console.error("getUserItems => error: ", error);
    });

  //  this.setState(() =>({
    //    Keys,
      //  test: 'testString'
   // }));

    console.log("Keys inside: ", Keys);
};


queryKeys(keys) {
    const items = [];


    console.log("queryKeys Called!");
    console.log("queryKeys :", keys);
    console.log('test: ', this.test);



    keys.forEach(function(Key, CollectionRef)  {

        console.log("Key array: ", Key);
        console.log("CollectionRef array: ", CollectionRef);

        firebase.firestore
            .collection('a').doc('b')
            .collection(CollectionRef)
            .doc(Key)
            .get().then(function (doc) {

            console.log("doc received");

            const {Name, imageDownloadUrl, Location} = doc.data();

            items.push({
                key: doc.id,
                doc, // DocumentSnapshot
                Name,
                imageDownloadUrl,
                Location,
            });

        }).catch(function (error) {
            console.error("queryKeys: error: ", error);
        })

    }) // forEach end

    this.setState({
        items
    });

}
更新:


我决定采用一种不同的方法,我只需在结尾调用
queryKeys
函数,然后在
getUserItems
中,将键作为参数传入即可。这种方法在正确的时间获取阵列时似乎有效,但现在我从firestore收到一个错误:

当我这样做时:

firebase.firestore
        .collection('a').doc('b')
        .collection('c')
        .doc('docID').get()
        .then((doc) => {
如何通过id获取文档


谢谢

我在下面所做的修改太脏了,我怀疑您的问题是,在执行循环之前,您正在上述两种方法中调用setState

如果同步循环,在循环内执行异步操作,退出循环(同步),并调用setState,期望数组中填充循环内获取的数据,那么这不会发生,因为您不会等待对firebase的AJAX请求

我在下面所做的是将对setState的调用放在每个循环中承诺的解析中,这并不理想(事实上,这对于生产来说是一个糟糕的想法),因为它将更新列表中每个项目的状态,而不是在收集完所有数据之后。你需要做一个循环,有很多方法可以做到这一点。不过,它应该能说明这一点,而且你应该能在屏幕上看到数据

constructor() {
    super();

    this.getUserItems = this.getUserItems.bind(this);


    this.state = {
        Name: '',
        Location: '',
        items: [],
        Keys: [],
        test: ''
    };
}

componentDidMount() {
    console.log('UserProfile');

    this.getUserItems();
    this.queryKeys();

}


getUserItems = () => {

    const Keys = [];

    const userCollectionRef = firebase.firestore()
        .collection('a').doc('b')
        .collection('c')




    userCollectionRef.get()
        .then((querySnapshot) => {
            console.log("user doc received");

            querySnapshot.forEach(function (doc) {

                console.log('Doc.id: ', doc.id);
                console.log('Doc.Key: ', doc.data().Key);
                console.log('Doc.CollectionRef: ', doc.data().CollectionRef);

                const {Key, CollectionRef} = doc.data();

                Keys.push({
                    Key,
                    CollectionRef
                })


            });

              this.setState(() =>({
                    Keys,
                    test: 'testString'
                }));

        }).catch(function (error) {
        console.error("getUserItems => error: ", error);
    });



    console.log("Keys inside: ", Keys);
};


queryKeys() {
    const items = [];


    console.log("queryKeys Called!");
    console.log("queryKeys :", this.state.Keys);
    console.log('test: ', this.test);



    this.state.Keys.forEach(function(Key, CollectionRef)  {

        console.log("Key array: ", Key);
        console.log("CollectionRef array: ", CollectionRef);

        firebase.firestore
            .collection('a').doc('b')
            .collection(CollectionRef)
            .doc(Key)
            .get().then(function (doc) {

            console.log("doc received");

            const {Name, imageDownloadUrl, Location} = doc.data();

            items.push({
                key: doc.id,
                doc, // DocumentSnapshot
                Name,
                imageDownloadUrl,
                Location,
            });

         this.setState({
             items
         });

        }).catch(function (error) {
            console.error("queryKeys: error: ", error);
        })

    }) // forEach end



}
下面您将看到一个粗略的示例,说明如何使用async&await使循环异步,不确定Firebase API是否能很好地处理这个问题,您可能需要阅读一下他们的文档

queryKeys() {
    const items = [];


    console.log("queryKeys Called!");
    console.log("queryKeys :", this.state.Keys);
    console.log('test: ', this.test);



    this.state.Keys.forEach(async function(Key, CollectionRef)  {

        console.log("Key array: ", Key);
        console.log("CollectionRef array: ", CollectionRef);

        try {
            let result = await firebase.firestore
            .collection('a').doc('b')
            .collection(CollectionRef)
            .doc(Key)
            .get();


            const {Name, imageDownloadUrl, Location} = result.data();

            items.push({
                key: doc.id,
                doc, // DocumentSnapshot
                Name,
                imageDownloadUrl,
                Location,
            });
        } catch (e) {
            console.error("queryKeys: error: ", error);
        }
    }) // forEach end


    this.setState({
        items
    })

}

由于代码的异步性质,在循环完成之前,正在调用setState。您需要在项目全部完成后设置状态
getUserItems
queryKeys
都执行异步函数
getUserItems
在调用
queryKeys
后设置状态,因为它从外部源获取数据
getUserItems
应该返回一个承诺,或者您可以使用
async/await
,但是它应该返回
,然后将它们传递给
queryKeys
我尝试在“getUserItems”函数的末尾调用“queryKeys”函数。然后在for循环之后,但调用queryKeys函数时遇到问题,我不断收到错误,说queryKeys不起作用。尽管我觉得这样做更好。谢谢你们的评论谢谢你们的回答,但是我改变了我的方法,你能告诉我我在做什么吗,这导致了FireStore的错误你改变了方法,因此你应该创建一个新问题,我的朋友;)