简体   繁体   English

如何将异步数据放入 React.js 中的全局数组中?

[英]How to get asynchronous data into a global array in React.js?

I want to insert asynchronous data from Firestore into React elements.我想将 Firestore 中的异步数据插入到 React 元素中。 I have a couple of functions that handle the flow.我有几个处理流程的函数。

getEvents() is an asynchronous function that returns an array of objects that is my data from Firestore. getEvents()是一个异步函数,它返回一个对象数组,这些对象是我从 Firestore 获得的数据。

const getEvents = async() => {
    try {
        const data = query(collection(db, id));
        const events = [];
        const snapshot = await getDocs(data);
        snapshot.forEach((doc) => events.push(doc.data()));
        return events;
    } catch(error) {
        console.error(error);
    }
}

This function is referenced in receiveEvents() where I take the returned data and put it into a global array in order to use it in the DOM.该函数在receiveEvents()中被引用,我在其中获取返回的数据并将其放入一个全局数组中,以便在 DOM 中使用它。

let userEvents = [];
const receiveEvents = () => {
    getEvents()
        .then(result => userEvents = result)
        .catch(error => console.error(error));

This function is used in displayEvents() to paste the returned data into the desired element.此函数用于displayEvents()将返回的数据粘贴到所需的元素中。 The function is called upon a button click.该函数在按钮单击时调用。

const displayEvents = () => {
    try {
        const btnContainer = document.querySelector(".btn-container");
        ReactDOM.render(<AppNavigation />, btnContainer);
        receiveEvents().then(() => { return userEvents }); 
    } catch(error) {
        console.error(error);
    }
}

I get an error index.js:1 TypeError: Cannot read properties of undefined (reading 'then') @ displayEvents .我收到错误index.js:1 TypeError: Cannot read properties of undefined (reading 'then') @ displayEvents

These functions use the logged user ID to access the right directory in the database.这些函数使用记录的用户 ID 访问数据库中的正确目录。 I retrieve the ID in a given function declared at the top of the file.我在文件顶部声明的给定函数中检索 ID。

let id = null;
const getUserId = () => {
    try {
        console.log("getUserId()");

        return auth.currentUser.uid;
    } catch(error) {
        console.error(error);
    }
}

The <AppNavigation/> component returns a div , namely: <AppNavigation/>组件返回一个div ,即:

<div className="arrow-navigation-container">
      <button className="arrow-btn"><span className="icon arrow">arrow_back</span></button> 
      <button className="arrow-btn"><span className="icon arrow">arrow_forward</span></button>
</div>

What can I do to get the asynchronous data into the userEvents array, so I can show it to the user upon request?我可以做些什么来将异步数据放入userEvents数组中,以便我可以根据请求向用户展示它?

I would use hooks for this personally:我个人会为此使用钩子:

  • useState for storing the data useState 用于存储数据
  • useEffect for triggering the fetching of the data useEffect 用于触发数据的获取
  • useContext for providing the data for whatever component that needs the data. useContext 为需要数据的任何组件提供数据。

Examples how to use those hooks: https://reactjs.org/docs/hooks-reference.html#usestate如何使用这些钩子的示例: https ://reactjs.org/docs/hooks-reference.html#usestate

The useState would go into the same component as the useContext Provider, usually in example apps it's in component. useState 将进入与 useContext Provider 相同的组件,通常在示例应用程序中它位于组件中。 The component which needs the data needs to be a child of the Context.Provider, but it doesn't need to be a direct child.需要数据的组件需要是 Context.Provider 的子组件,但不需要是直接子组件。

useEffect goes also to the same component, and with the dependencies you can decide if you want to fetch the data only once or for example when that ID changes. useEffect 也适用于同一个组件,并且通过依赖项,您可以决定是只获取一次数据,还是例如在该 ID 更改时获取数据。

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

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