简体   繁体   English

我应该在哪里从Reactjs应用程序中获取数据?

[英]Where should I fetch data in Reactjs app?

I have been creating a Reactjs app. 我一直在创建一个Reactjs应用程序。 I have encountered a problem and want to know where to fetch data from firebase. 我遇到了一个问题,想知道从Firebase哪里获取数据。 Is it better to fetch collections of data in the root component(App.jsx) or in individual components? 在根组件(App.jsx)或单个组件中获取数据集合是否更好?

For now, I have users, products and sales collections. 现在,我有用户,产品和销售集合。 Some components use data from the same collection. 一些组件使用相同集合中的数据。 Ex: Payments component also uses Sales collection data for analytics. 例如:“付款”组件还使用“销售”收款数据进行分析。

Case 1: If I fetch data in the root component I do not have to fetch inside the components. 情况1:如果我在根组件中获取数据,则不必在组件内部获取数据。

Case 2: If I fetch data inside components I will fetch the same data twice for different components in different routes. 情况2:如果我在组件内部获取数据,则将针对不同路径中的不同组件获取两次相同的数据。

Please, advice me the better way of handling the situation. 请给我建议更好的处理情况的方法。

You tagged Redux in your question so I assume you are using it in your React App? 您在问题中标记了Redux ,所以我假设您在React App中使用了Redux

If you are using Redux , place all of your fetching in your actions files. 如果您正在使用Redux ,请将所有提取内容放入actions文件中。 If there are other components that are listening to the state that are affected by the fetch, it will automatically re-render the component data. 如果还有其他正在侦听受提取影响的状态的组件,它将自动重新呈现组件数据。 No need for you to do the fetching twice. 无需您进行两次提取。

Case 1:- if you fetch all the data from root component. 情况1:-如果您从根组件中获取所有数据。 you will be dealing with lot of data in the beginning , will slow down the initial loading of the app (but should be fine for very tiny apps). 一开始您将要处理大量数据,这会减慢应用程序的初始加载速度(但对于非常小的应用程序应该没问题)。 Not recommended for medium-large scale apps. 不建议用于中大型应用程序。
case 2:- This approach is fine but will increase a small delay in all the components(for getting the data from API), but if you are concerned about the bandwidth usage & latency. 情况2:-这种方法很好,但是会增加所有组件的较小延迟(用于从API获取数据),但是如果您担心带宽使用和延迟。 you should think about a unified data store like redux. 您应该考虑使用像redux这样的统一数据存储。 Fetch the data once using actions/sideEffects from redux/thunk etc, keep it in the redux store. 使用来自redux / thunk等的action / sideEffects一次获取数据,并将其保存在redux存储中。 consume the same data in every other components. 在所有其他组件中消耗相同的数据。

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

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