简体   繁体   English

如何在首次渲染之前在Redux中获取数据并将其设置为默认状态

[英]How to fetch data in redux before first render and set it to default state

I have dropdown filter to show items by date, for example and show data for last 24 hours, show data for last 3 days. 我有下拉过滤器,以按日期显示项目,例如,显示过去24小时的数据,显示过去3天的数据。

I have defaultState in my reducer 我的reducer中有defaultState

const defaultState = {
  dataArray: [],
  a: true,
  b: false
}

By default dataArray is empty. 默认情况下, dataArray为空。 And I have reducer and action. 而且我有减速器和动作。 In componentDidMount method I fetch data from server by dispatching some actions. 在componentDidMount方法中,我通过调度一些操作从服务器获取数据。 If I refresh page, default page that list last items for 24 hours is empty because dataArry comes from defaultState in my reducer. 如果刷新页面,则列出最后24小时的项目的默认页面为空,因为dataArry来自我的reducer中的defaultState。 But if I change page to list data for last 3 days then componentWillReceiveProps works and inside this method I fetch data and it reduce my state and returns new one with 但是,如果我更改页面以列出最近三天的数据,则componentWillReceiveProps可以正常工作,并且在此方法中,我可以获取数据,它会减少状态并返回带有

dataArray = [{some data}]

How to fetch data and set it to state to render it after page was refreshed? 如何获取数据并将其设置为刷新页面后呈现的状态?

Add to defaultState a 'loading' variable and initialize it to true. 向defaultState添加一个“加载”变量,并将其初始化为true。 When fetching of data is completed, set it to false. 数据获取完成后,将其设置为false。

In your component check this variable. 在您的组件中检查此变量。 If it is true display a spinner and/or a loading message, otherwise display the data. 如果为true,则显示微调框和/或加载消息,否则显示数据。

In addition to that, every time you start fetching, before fetching, fire an action called 'FETCH_START' which will set the loading variable to true. 除此之外,每次您开始提取之前,都要在提取之前触发一个名为“ FETCH_START”的操作,该操作会将加载变量设置为true。

If there is an error in fetching, you can set another state variable to the error message. 如果获取时出错,则可以将另一个状态变量设置为错误消息。 This variable will be initialized (every time you start fetching) to an empty string. 该变量将被初始化(每次您开始获取)为空字符串。 If loading is completed you can check this error variable, and display the error message if there was an error, instead of displaying the data. 如果加载完成,则可以检查此错误变量,如果有错误,则显示错误消息,而不是显示数据。

This process is useful for various cases, such as authentication, etc. 此过程对于各种情况(例如身份验证等)很有用。

Yossi's answer is pretty spot on. Yossi的答案很明确。 I just want to take it a step further and mention that you can also enhance your users' experience by knowning when to fetch data. 我只是想更进一步,并提到您还可以通过了解何时获取数据来增强用户的体验。 For instance, if you're on a landing page and know most of your users are going to be browsing your store, start fetching that data on the landing page while nothing is happening. 例如,如果您在登录页面上并且知道大多数用户将要浏览您的商店,则在什么都没有发生的情况下开始在登录页面上获取该数据。

To go along with that, take a look at this: Google Dev's requestIdleCallback() 为此,请看一下: Google Dev的requestIdleCallback()

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

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