简体   繁体   English

在 React 中访问嵌套的 Firestore 数据?

[英]Access Nested Firestore Data in React?

I've been having this issue for the past few hours now, and the only reason I'm posting a question so quickly is because there doesn't seen to be too much information on this topic, or at least this specific point.在过去的几个小时里,我一直遇到这个问题,我这么快发布问题的唯一原因是因为没有看到关于这个主题的太多信息,或者至少没有看到这个特定的点。

I currently have a cloud function that grabs and saves data from a third-party API into my Firebase Firestore Database.我目前有一个云 function,它从第三方 API 抓取数据并将其保存到我的 Firebase Firestore 数据库中。 In my frontend application I'm using React and attempting to display this data by mapping it to list Items.在我的前端应用程序中,我使用 React 并尝试通过将其映射到列表项来显示此数据。 All high level items in the tree are fine to reach, and all the data from those is already displaying properly.树中的所有高级项目都可以访问,并且其中的所有数据都已经正确显示。

Any nested item though, returns with 'Cannot read property of undefined'.但是,任何嵌套项目都会返回“无法读取未定义的属性”。 When console logging my top level container all subsequent data displays in the terminal.当控制台记录我的顶级容器时,所有后续数据都显示在终端中。 I can break it down all the way to the top level Array which shows me this structure:我可以将它一直分解到顶层 Array,它向我展示了这个结构:

从 firebase 返回的数组之一的控制台输出

I need to access the keys within those objects, but as I mentioned earlier this is what I'm greeted with when I try to do so:我需要访问这些对象中的键,但正如我之前提到的,当我尝试这样做时,我会遇到这样的情况:

Uncaught TypeError: Cannot read property 'title' of undefined
    at ProductScreen (ProductScreen.js:56)

Also Here is the code from the current screen I'm working on, and how I am trying to access the data:此外,这是我正在处理的当前屏幕的代码,以及我如何尝试访问数据:

import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { detailsProduct } from '../actions/productActions';

const ProductScreen = (props) => {
    const [qty, setQty] = useState(1);
    const productDetails = useSelector(state => state.productDetails);
    const { product, loading, error } = productDetails;
    const resp = props.match.params.id;
    const dispatch = useDispatch();

    useEffect(() => {
        dispatch(detailsProduct(resp));
        return () => {
            //
        };
    }, []);

    const handelAddToCart = () => {
        props.history.push(`/cart/${resp}/?qty=${qty}`)
    }

    return <div>
        <div className='back-to-result'>
            <Link to='/'>Back to Results</Link>
        </div>
        {loading ? <div>Loading...</div> :
            error ? <div>{error}</div> :
                (
                    <div className='details'>
                        <div className='details-image'>
                            <img src={product.thumbnailImage //This ever comes through as well} alt='product'></img> 
                        </div>
                        <div className='details-info'>
                            <ul>
                                <li>
                                    <h4>{product.title}</h4> //This data comes through fine.
                                </li>
                                <li>
                                    {product.rating} Stars ({product.numReviews} Reviews)
                                </li>
                                <li>
                                    <b>{product.variants.price}</b>
                                </li>
                                <li>
                                    Description:
                                    <div>
                                        {product.description // This data comes through fine} 
                                    </div>
                                    <div>
                                        <select>
                                            {
                                            console.log(product.sizes.title // Here is where I am trying to console log the Size Title) 
                                            }

                                        </select>
                                    </div>
                                </li>
                            </ul>
                        </div>
                        <div className='details-action'>
                            <ul>
                                <li>
                                    <b>Price:</b> ${product.variants.price // This data does not come through either, has the same error} 
                                </li>
                                <li>
                                    Status: Currently Unavailable
                                </li>
                                <li>
                                    Qty: <select>
                                            <option>1</option>
                                            <option>2</option>
                                            <option>3</option>
                                            <option>4</option>
                                    </select>
                                </li>
                                <li>
                                    <button className='button' onClick={handelAddToCart}>Add to Cart</button>  
                                </li>
                            </ul>
                        </div>
                    </div>
                )
        }
    </div>
}

export default ProductScreen

I'm not sure where or what I'm doing wrong.我不确定我在哪里或做错了什么。 Any help would be greatly appreciated.任何帮助将不胜感激。 Thank you.谢谢你。

*Apologies for not including the main code initially, wasn't sure if it was going to be helpful If all I was doing was console logging, but I hop this is able to give a better perspective on the situation. *抱歉最初没有包含主要代码,不确定它是否会有所帮助如果我所做的只是控制台日志记录,但我希望这能够更好地了解情况。

I managed to figure out what was wrong, after many many console.logs I found a weird issue with how my data was entering my app.我设法弄清楚出了什么问题,在许多控制台日志之后,我发现了一个奇怪的问题,即我的数据如何进入我的应用程序。 After a bit more research I found a Stackoverflow question on React state, and that's what my issue was.经过更多研究后,我在 React state 上发现了一个 Stackoverflow 问题,这就是我的问题所在。 Inside my state control through Redux I only had my top level object with an initial state of {}, but what I discovered is that in the case of an object, you also need to set the initial state of any arrays within that object, and if you are returning objects inside those arrays you also need to set the state for those as well. Inside my state control through Redux I only had my top level object with an initial state of {}, but what I discovered is that in the case of an object, you also need to set the initial state of any arrays within that object, and如果您要返回那些 arrays 内的对象,您还需要为这些对象设置 state。 This would end up looking like this:这最终看起来像这样:

state = { mainObj: { array: [], arrayWithObj: [{}]} }

And you would continue doing this for your whole data structure.您将继续为您的整个数据结构执行此操作。 This is all being done in my Redux reducer function.这一切都在我的 Redux 减速机 function 中完成。 The only caveat to not have to do this, is if your top level item is an array, then you don't have to break down this structure, at least thats what I experienced on one of my other pages that had that.唯一不必这样做的警告是,如果您的顶级项目是一个数组,那么您不必分解此结构,至少这是我在其他具有该结构的页面中所经历的。

I hope this helps anyone else with this issue.我希望这可以帮助其他人解决这个问题。

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

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