react钩子

Repo found here: https://github.com/maisonm/paginate_example

仓库在这里找到: https : //github.com/maisonm/paginate_example

Recently I had to come up with a way to paginate a data view in a React app. This data view could fetch an array that could contain up to 5000 objects, or as few as 100. This meant, that regardless of the length of the incoming array, I needed to be able to dynamically determine how many pages could be made from this array given the total number of items I wanted shown per page.

最近,我不得不想出一种在React应用程序中对数据视图进行分页的方法。 该数据视图可以获取一个最多可包含5000个对象或少至100个对象的数组。这意味着,无论传入数组的长度如何,我都需要能够动态确定可以从中创建多少页数组给出了我希望每页显示的项目总数。

For an abstracted example, let’s say we have the following: 100 data objects in the array and we want to show 20 of these data objects per page. That would mean that there are only 5 total pages possible: 100/20 = 5.

对于一个抽象的示例,假设我们有以下内容:数组中有100个数据对象,我们希望每页显示20个这些数据对象。 这意味着总共可能只有5页:100/20 = 5。

But what if we had an odd number on both sides? Take this for example: 125 data objects and we only want 18 objects per page. The math works out to be: 6.94 pages, or for our sake 7. So in this case, we would end up with a 7th page that contained any leftovers.

但是,如果我们双方都有一个奇数怎么办? 以这个为例:125个数据对象,我们每页只需要18个对象。 数学计算结果为:6.94页,或者为了我们的缘故7。因此,在这种情况下,我们将得到第7页,其中包含所有剩余的内容。

There was another critical reason to do this: speed. At any given time my app could see up to 3000 returned data objects to show. This is a very large list, and that’s a whole lot of render time if you ask me. On top of that, it’s extremely tasking for the browser to handle. React will throw a warning if 200 or more unique divs are created, and more than likely, your browser will lock up.

这样做还有另一个关键原因:速度。 在任何给定时间,我的应用程序最多可以看到3000个要显示的返回数据对象。 这是一个很大的列表,如果您问我,这将花费大量渲染时间。 最重要的是,浏览器要处理非常艰巨的任务。 如果创建了200个或更多的唯一div,React会发出警告,并且浏览器可能会锁定。

Storing a huge array in state is no issue. It costs almost nothing to store data in a component’s state. But rendering that data is where it can be tricky.

在状态中存储大量阵列是没有问题的。 在组件状态下存储数据几乎不花任何钱。 但是渲染该数据可能很棘手。

With a paginated view, we would only be rendering a fraction of those data objects. Regardless the length of the array returned from the API call. We may pass in an array of 5000 objects from the initial API call, but if for example, we only want to show 28 objects per page, well, then we are only rendering out 28 data objects at a time in each lifecycle of the view rendering component.

使用分页视图,我们将只渲染这些数据对象的一部分。 无论从API调用返回的数组的长度如何。 我们可能会从初始API调用中传入5000个对象的数组,但是例如,如果我们只希望每页显示28个对象,那么,在视图的每个生命周期中一次仅渲染28个数据对象。渲染组件。

Below I will go into detail on how I created this Pagination component, with an in-depth example using a fake users list. I am assuming a few things about you here:

下面,我将详细介绍如何创建此分页组件,并提供一个使用伪造用户列表的深入示例。 我在这里假设一些关于您的事情:

  • You are familiar with React您熟悉React
  • You are familiar with Express (used for the dummy API)您熟悉Express(用于虚拟API)

I will not be going over the React basics, and I will not be touching on the Express server this example is tied to. This example is also making use of styled-components. More on that here: https://styled-components.com/docs

我不会讲解React基础知识,也不会接触这个示例所依赖的Express服务器。 此示例还利用了样式化组件。 此处的更多信息: https : //styled-components.com/docs

进行设定 (Getting Setup)

First, clone the Github repo found here: https://github.com/maisonm/paginate_example

首先,克隆在此处找到的Github存储库: https : //github.com/maisonm/paginate_example

Once it is cloned locally, go ahead and use npm (or yarn if you prefer) to install the dependencies for both the root and client directories.

一旦在本地克隆它,继续并使用npm(如果需要,可以使用yarn)为根目录和客户端目录安装依赖项。

After that, you should be able to fire up both the server and client. We need the server running so that our React client can proxy any API calls to it. We are making one GET request to our Express server: /users/getAllUsers. Getting a list of users is the API’s sole purpose in this example. You can checkout the code for this API route in /bin/api/controllers.

之后,您应该能够启动服务器和客户端。 我们需要服务器运行,以便我们的React客户端可以代理对它的任何API调用。 我们正在向Express服务器发出一个GET请求:/ users / getAllUsers。 在此示例中,获取用户列表是API的唯一目的。 您可以在/ bin / api / controllers中签出此API路由的代码。

Yes, there are probably simpler ways to feed dummy data into an example like this, but with Express we can do this making an actual API call, and that is what I wanted to do.

是的,可能有更简单的方法将伪数据输入到这样的示例中,但是使用Express,我们可以进行实际的API调用,而这正是我想要做的。

组件概述 (Components Overview)

Here is what the final product will look like:

这是最终产品的外观:

In this example, we have the following components:

在此示例中,我们具有以下组件:

  • UsersPage

    UsersPage

  • UsersTable

    UsersTable

  • Paginate

    Paginate

The UsersPage component is responsible for setting up a page to contain UsersTable which makes use of the Paginate component.

UsersPage组件负责建立一个网页包含UsersTable这使得使用的Paginate组件。

UsersTable is responsible for making an API call for a list of users, setting up a table view and rendering the returned API data into that table view. This is the component that we use Paginate within. Once the API data call has returned, we then pass this returned data into Paginate, which then determines how many total pages are possible from the passed in data array.

UsersTable负责对用户列表进行API调用,设置表视图并将返回的API数据呈现到该表视图中。 这是我们在其中使用Paginate的组件。 API数据调用返回后,我们便将此返回的数据传递给Paginate ,后者从传入的数据数组中确定总共有多少页。

Paginate houses it’s own controls to that allow someone to click through the page numbers. This component will determine what data set should be shown given the selected page, and sends that data set back into UsersTable to be rendered. So in reality, our UsersTable is being told what to render by Paginate, with the exception of the initial mounting of UsersTables, which I will touch on in more depth when we get there.

Paginate包含它自己的控件,允许某人单击页码。 该组件将确定在给定所选页面的情况下应显示哪些数据集,并将该数据集发送回UsersTable以进行呈现。 因此,在现实中,我们的UsersTable被告知由呈现什么Paginate ,与初始安装除外UsersTables ,其中当我们到达那里,我会触及更深入。

Paginate.js (Paginate.js)

This component is the driving force behind our data view. It handles the paginating! Let’s break it down piece by piece.

该组件是我们数据视图背后的驱动力。 它处理分页! 让我们逐一分解。

Note: This component utilizes the Font Awesome React library for it’s arrow icons. I was already using FA throughout my App so I stuck with it, but you could substitute these with whatever assets you like. More here: https://fontawesome.com/how-to-use/on-the-web/using-with/react

注意:该组件将Font Awesome React库用于其箭头图标。 我已经在整个App中都使用了FA,所以我坚持使用它,但是您可以用任何喜欢的资产替换它们。 此处更多内容: https : //fontawesome.com/how-to-use/on-the-web/using-with/react

道具 (Props)

Paginate.js props
Paginate.js道具

Paginate doesn’t need much to be satisfied. Let’s take a look at what it’s props do:

Paginate不需要太多满足。 让我们看一下道具的作用:

  • data — It is what it sounds like. Paginate expects this prop to contain an array of data. Nothing more, nothing less.

    data -听起来就是这样。 Paginate希望此道具包含数据数组。 仅此而已。

  • setData — This should be a function that is passed in by the parent. Paginate will use this function via props to set the state of the parent component with data. This is how UsersTable in this example, will get data to render the pages.

    setData —这应该是父级传递的函数。 Paginate将通过props使用此功能来设置带有数据的父组件的状态。 这就是本例中的UsersTable将如何获取数据以呈现页面。

  • itemsPerPage — This is why Paginate knows how many items to show per page. You tell it.

    itemsPerPage —这就是为什么Paginate知道每页显示多少个项目的原因。 告诉你

州 (State)

Paginate.js state
Paginate.js状态

The state for the Paginate component in all of its greatness. This component receives an array of data via props. In our example, it’s receiving an array of users. Let me explain each variable:

Paginate组件的状态非常Paginate 。 该组件通过prop接收数据数组。 在我们的示例中,它正在接收一系列用户。 让我解释一下每个变量:

  • totalPages — The total number of pages possible given the length of the passed in array of data. This will be set when the component mounts, or when it receives a fresh new data set.

    totalPages —给定传入数据数组的长度,可能的总页数。 将在安装组件时或在接收到新的数据集时进行设置。

  • dataStartingIndex is set when the Paginate component determines how many pages it can create with the given array. Paginate is a child component of parent UsersTable. When our UsersTable first mounts, it does not have access to any paginated data because our Paginate component doesn’t mount until the parent component containing it does. This means, we need to have an initial data set created when UsersTable mounts for the first time. For example, if we want to render 4 objects per page, UsersTable handles creating and rendering the first 4 sets of data in the users array returned from the API call, and lets Paginate know via dataStartingIndex that it can start it’s first computed data set at index 4 of the users array when it mounts and receives it’s props. This is how we avoid an empty UsersTable on first mount. More on this later, so don’t worry if you are lost here!

    Paginate组件确定使用给定数组可以创建多少页时,将设置dataStartingIndexPaginate是父UsersTable的子组件。 当我们的UsersTable首次安装时,它无权访问任何分页数据,因为我们的Paginate组件直到包含它的父组件才安装。 这意味着,我们需要在UsersTable安装UsersTable时创建一个初始数据集。 例如,如果我们想呈现每页4个对象, UsersTable处理创建和渲染第4套从API调用返回的用户阵列中的数据,并允许Paginate通过知道dataStartingIndex它可以启动它的第一个计算的数据设定在挂载并接收道具时,用户数组的索引4。 这就是我们避免在第一次安装时出现空的UsersTable 。 稍后再详细介绍,所以不要担心您迷路了!

  • dataLastIndex — This is to keep track of the last index we stopped at in the data array. If we requested the 0–5 indexes, the component needs to know to start at index 6 when the next page is requested. And so-on and so-forth as we click forward and backward through the pages. It is basically a placeholder in the array of users.

    dataLastIndex —这是为了跟踪我们在数据数组中停止的最后一个索引。 如果我们请求0–5索引,那么当请求下一页时,组件需要知道从索引6开始。 前后单击页面,如此反复。 它基本上是用户数组中的占位符。

  • currentClickedNumber —Is exactly what it sounds like. This keeps track of what page is currently selected. This is set by clicking on either a page number, or the navigation arrows. Keeping track of what page number we are on, lets us display the proper page number.

    currentClickedNumber确实是这样。 这样可以跟踪当前选择的页面。 通过单击页码或导航箭头进行设置。 跟踪我们正在使用的页码,可以让我们显示正确的页码。

  • pageData — The current page data set to be sent back to the parent component UsersTable. The Paginate component takes in the raw array of data, determines which indexes from this array to pull, and then sets those ‘pulled’ indexes to state. pageData will contain only the data to be rendered for the requested page, and once it updates, it is passed back to UsersTable to be rendered as a page. To put it simply, this variable in state will be updated with the data associated with the page you are clicking on (requesting).

    pageData —当前页面数据集,该数据集将发送回父组件UsersTablePaginate组件接收原始数据数组,确定要从该数组中拉出哪些索引,然后将这些“拉出”的索引设置为state。 pageData将仅包含要为请求的页面呈现的数据,并且一旦更新,它将被传递回UsersTable以呈现为页面。 简而言之,该状态变量将使用与您单击(请求)页面相关的数据进行更新。

确定页数 (Determining Number Of Pages)

determineNumberOfPages()
defineNumberOfPages()

Step one of the Pagination component is to first determine how many pages it can make given two variables: the length of the incoming data array received via props, and the number of items we intend to show per page (also received via props).

Pagination组件的第一步是,首先确定给定两个变量,它可以创建多少个页面:通过props接收的传入数据数组的长度,以及我们打算在每页上显示的项目数(也通过props接收)。

This function takes the data array and itemsPerPage integer from props and then determines how many pages we need to accommodate our specified itemsPerPage. On lines 9-12 in the above gist, we create a chunk of data for each page. The chunkArray will hold each pages chunk of data. And that index in the chunkArray is also the page the data set is for.

此函数从props获取data数组和itemsPerPage整数,然后确定需要容纳多少页才能容纳指定的itemsPerPage 。 在上述要点的lines 9-12 ,我们为每个页面创建了一个数据块。 chunkArray将保存每个页面的数据块。 而且chunkArray中的索引也是数据集的页面。

So for example let’s say we have this as our chunk array (pretend the numbers are users for brevity): chunkArray = [[1,2,3],[4,5,6],[7,8]]

举例来说,假设我们将其作为块数组(假设数字是简短起见,请假设用户是这样): chunkArray = [[1,2,3],[4,5,6],[7,8]]

In this array, we are only requesting 3 items per page. You can see that because each data chunk array has only 3 items. The reason the 3rd data chunk in the array is only showing 2 indexes is because we only wanted to show 3 items per page, but we had 8 ‘users’ in the data set. We know 3 does not divide evenly into 8, so the remaining page will not be full.

在此数组中,我们每页仅请求3个项目。 您会看到,因为每个数据块数组只有3个项目。 数组中的第三个数据块仅显示2个索引的原因是,我们只希望每页显示3个项目,但是数据集中有8个“用户”。 我们知道3不会平均分成8,因此剩余页面将不会满。

On lines 14–16 in the above gist, this is where we construct the users object we are going to put into state as pageData. This is what we render pages from. We loop through chunkArray and for each data set within it, we assign that data set to object paginatedDataObject found on line 3. Here is what paginatedDataObject looks like after the loop:

在上面要点的第14至16行上,我们在此处构造将要放入状态的用户对象pageData 。 这就是我们渲染页面的依据。 我们遍历chunkArray并为其中的每个数据集将数据集分配给在第3行找到的对象paginatedDataObject 。这是循环后paginatedDataObject样子:

Once more, are the chunks of data we ended up with in chunkArray:

再一次,是我们最终在chunkArray得到的数据块:

chunkArray = [[1,2,3],[4,5,6],[7,8]]

chunkArray = [[1,2,3],[4,5,6],[7,8]]

The final result after looping through chunkArray and creating paginatedDataObject:

遍历chunkArray并创建paginatedDataObject后的最终结果:

paginatedDataObject = { 1: [1,2,3], 2: [4,5,6], 3: [7,8] }

paginatedDataObject = { 1: [1,2,3], 2: [4,5,6], 3: [7,8] }

In the loop done on lines 14–16 you’ll notice we add a 1 to the index count. As we know, array indexes start at 0. For UI/UX purposes we want to show 1,2,3,4,5 and so on and so forth. To do this, we need to add 1 so that we can properly match up paginatedDataObject’s properties with our page number clicks.

在第lines 14–16的循环中,您会注意到我们在索引计数上添加了1 。 众所周知,数组索引从0开始。出于UI / UX的目的,我们希望显示1,2,3,4,5,依此类推。 为此,我们需要加1以便我们可以正确匹配paginatedDataObject's属性与页码的点击次数。

You can see start to see how this is going to work. If you were to click on page 2, that page is rendering from the array [4,5,6] found at paginatedDataObject.2, and so on and so forth as you go through the available pages. The properties of paginatedDataObject reference page numbers.

您可以开始看到它是如何工作的。 如果要单击页面2,则该页面是从在paginatedDataObject.2找到的数组[4,5,6]呈现的,依此类推,依次浏览可用页面。 paginatedDataObject的属性参考页码。

Now we need to put all of that into Paginate state:

现在我们需要将所有这些都设置为Paginate状态:

Paginate.js
Paginate.js

At the end determineNumberOfPages() we set state. totalPages is determined by the length of chunkArray, dataStartingIndex is determined by the itemsPerPageProp, and pageData comes from paginatedDataObject. Since determineNumberOfPages() runs only runs on mount (or when it gets new data), we go ahead set clickedOnNumber to 1 to signifying we are already on the 1st page, because it was rendered by UsersTable.

在结束determineNumberOfPages()我们设置状态。 totalPageschunkArray的长度确定, dataStartingIndexitemsPerPageProp确定,而pageData来自paginatedDataObject 。 由于clickedOnNumber determineNumberOfPages()仅在安装时(或在获取新数据时)运行,因此我们将clickedOnNumber设置为1表示我们已经在第一页上了,因为它是由UsersTable呈现的。

控制分页 (Controlling Pagination)

We need to be able to control the pagination! Meaning we need to be able to go from one page to the next and visa versa via some click action.

我们需要能够控制分页! 这意味着我们需要能够通过单击操作从一页转到另一页,反之亦然。

setCurrentClickedNumber(e) is a function that is used in an onClick method on the actual page numbers shown below:

setCurrentClickedNumber(e)是在如下所示的实际页码上的onClick方法中使用的函数:

Every time a page number is clicked, setCurrentClickedNumber is fired with an event argument passed via onClick. Inside of this event, we get access to event.target.innerText, which is the value of the clicked on number. We set this value to currentClickedNumber in state.

每次单击页码时,都会使用通过onClick传递的event参数触发setCurrentClickedNumber 。 在此事件内部,我们可以访问event.target.innerText ,它是单击编号的值。 我们将此状态设置为currentClickedNumber

All of the move forward and backward functions are pretty explicit in what they are doing. They are simply taking 1 or adding 1 to currentClickedNumber.

所有前进和后退功能在其工作中都非常明确。 他们只是将1或加1到currentClickedNumber

moveOnePageForward is the exception to the above statement and it requires a little bit more explaining.

moveOnePageForward是上述声明的例外,需要更多说明。

moveOnePageForward()
moveOnePageForward()

dataStartingIndex comes from the itemsPerPage prop, which we went over above. When UsersTable mounts initially, it builds an initial data set to render when it mounts. This is because Paginate can not mount until UsersTable does. All in all, this means we would not have access to an initial data set for page 1 on first mount, not unless that initial data set is created on the initial mount of UsersPage. If we want 4 users per page, that means we are using the objects found at the 0–3 indexes of our users array when UsersTable first mounts. Using the example of 4 users per page, after Paginate mounts, dataStartingIndex will allow it to start the page 2 data set at index 4 of our users array. Otherwise, it would start at index 0 and page 2 would be repeat the page 1 data set on the first page 2 click.

dataStartingIndex来自itemsPerPage dataStartingIndex ,我们在上面进行了介绍。 最初安装UsersTable ,它将构建一个初始数据集以在安装时呈现。 这是因为Paginate直到用户UsersTable才能装入。 总而言之,这意味着我们将无法在首次安装时访问页面1的初始数据集,除非该初始数据集是在UsersPage的初始安装上UsersPage 。 如果我们希望每个页面有4个用户,则意味着我们使用的是在首次挂载UsersTable时在users数组的0–3索引处找到的对象。 以每页4个用户为例,在安装Paginate后, dataStartingIndex将允许它在用户数组的索引4处启动第2页数据集。 否则,它将从索引0开始,并且第2页将重复第2页第一个单击上的第1页数据集。

A more in-depth explanation, the itemsPerPage prop comes from a state value set in UsersTable. UsersTable creates the first data set using the itemsPerPage value. It loops through the data array, and only pulls up to whatever index itemsPerPage is more than. If itemsPerPage = 5, then UsersPage is only going to create an initial page 1 data set with the first 5 indexes of the data array returned from the API call. This means that in Paginate when we go to page 2, we need to get it’s data set starting at index 5 in the users array.

更深入的解释是, itemsPerPage属性来自UsersTable设置的状态值。 UsersTable使用itemsPerPage值创建第一个数据集。 它循环遍历数据数组,并且仅拉至任何索引itemsPerPage不止itemsPerPage 。 如果itemsPerPage = 5 ,则UsersPage仅将使用API​​调用返回的数据数组的前5个索引来创建初始页面1数据集。 这意味着在Paginate当我们转到第2页时,我们需要获取它的数据集(从users数组的索引5开始)。

itemsPerPage is passed into Paginate, and is assigned to dataStartingIndex. This is how Paginate knows what index to start pagination on in the data array on first mount. On first mount of Paginate we have it default to page 1 which was rendered from the initial data set created in UsersTable. When we click the next navigation button for the first time, it goes to page 2 and this page 2 data set starts at whatever index dataStartingIndex is equal to. When dataStartingIndex has a value, it signifies everything has mounted and we are on page 1. When it is set to null, we are now working from the created data sets in Paginate and no longer care about or need the initial data set created on the first mount of UsersTable. Paginate is now keeping track of the last index it pulled data from in the data array from here on out or until you refresh the page.

itemsPerPage传递到Paginate ,并分配给dataStartingIndex 。 这就是Paginate如何知道在第一次安装时要在数据数组中开始分页的索引。 在第一次Paginate我们默认使用第1页,该页是从UsersTable创建的初始数据集UsersTable 。 当我们点击下一个导航按钮,第一次,它进入到第2页,这2页数据集开始不惜一切指标dataStartingIndex等于。 当dataStartingIndex有一个价值,它意味着一切都已经安装,我们是第1页。当它被设置为null,我们现在从创建的数据集工作Paginate和关于不再关心或需要设定上创建的初始数据首先安装UsersTablePaginate现在一直在跟踪它从这里开始直到刷新页面之前从数据数组中提取数据的最后一个索引。

渲染页码 (Rendering Page Numbers)

pageNumberRender() is called every-time the component is rendered or re-rendered. This allows us to render out the page numbers using the totalPages variable along with the currentClicked variable, both of which are located in state.

每次渲染或重新渲染组件时,都会调用pageNumberRender() 。 这使我们能够使用totalPages变量和currentClicked变量来呈现页码,这两个变量均处于状态。

This component is very simple, it only renders out a page number component that shows how many pages are available, and updates with the active page number. It also attached an onClick to each page number so that when clicked, the page numbers report back. Anytime a page number is clicked, the state is updated and we get a re-render. This re-render is when the page numbers update.

该组件非常简单,它仅呈现一个页面编号组件,该组件显示可用的页面数量,并使用活动页面编号进行更新。 它还将onClick附加到每个页码,以便在单击时,页码会报告回来。 只要点击页码,状态就会更新,我们会重新渲染。 当页码更新时,此重新呈现。

The isClicked prop is used in our styled component, to determine the styling change based on being active or inactive. This is simply a way to highlight the page number currently viewed.

在我们的样式化组件中使用isClicked道具,以根据活动或不活动来确定样式更改。 这只是突出显示当前查看的页码的一种方法。

生命周期方法 (Lifecycle Methods)

The lifecycle methods of Paginate.js are fairly simple and easy to digest. Firstly when the component mounts initially, componentWillMount() handles calling determineNumberOfPages(), which handles creating our paginated data sets. This lets us create and split apart our users data array based on how many users per page we want, and formats our data array so that it can be called by page numbers.

Paginate.js的生命周期方法非常简单且易于消化。 首先,当组件最初安装时, componentWillMount()处理调用determineNumberOfPages() ,该处理处理创建我们的分页数据集。 这使我们可以根据所需的每页用户数量来创建和拆分用户数据数组,并格式化数据数组,以便可以按页码进行调用。

And lastly, we need to monitor any props or state changes with componentDidUpdate(). This could be triggered by changing the page number, or a refresh of an updated users array. Simply, we keep track of the data coming in via props, and if it has changed, we run determineNumberOfPages() to handle creating a new pagination data set from the updated users array. Also, we monitor the page number clicks, and if the page changes, we update to that pages data set in state. When state changes, it forces a re-render, which is how the users list updates on page click.

最后,我们需要使用componentDidUpdate()监视任何道具或状态更改。 这可以通过更改页码或刷新更新的用户数组来触发。 简单来说,我们跟踪通过props传入的数据,如果数据已更改,我们将运行determineNumberOfPages()来处理根据更新后的users数组创建新的分页数据集。 另外,我们监视页面编号的点击次数,如果页面发生更改,我们将更新为状态中的该页面数据集。 状态更改时,它将强制重新渲染,这是用户列表在页面单击时更新的方式。

UserTable.js (UserTable.js)

The UserTable component is pretty straightforward, it handles 4 things; Fetching the data from the API, setting returned data into state, setting how many users per page we want to render, and of course rendering and passing all of this information into Paginate. You will also notice that this component is constructed using React Hooks.

UserTable组件非常简单,它处理4件事。 从API提取数据,将返回的数据设置为状态,设置我们要呈现的每页有多少用户,当然还要呈现并将所有这些信息传递给Paginate 。 您还将注意到该组件是使用React Hooks构建的。

We pass three variables as props to Paginate: data, setData and itemsPerPage. Since we have gone over the Paginate component already, we should know what these are for. data is what returns from the API call when UserTable mounts, setData is a function to update the UserTable state.

我们将三个变量作为道具传递给PaginatedatasetDataitemsPerPage 。 由于我们已经遍历了Paginate组件,因此我们应该知道它们的用途。 dataUserTable装入时从API调用返回的内容, setData是用于更新UserTable状态的函数。

updateDataFromPaginate() takes our state updating setDataFromPaginate() hook, and allows us to callback to it from a child component, that in turn will send back an argument that will be updated in the UserTable state. It goes against React’s best practices to send a raw updating hook directly into a child component via props, so we create this function that can call the hook, and be passed into a child. This function can then be used to callback to UserTable and use the state updating hook directly from UserTable.

updateDataFromPaginate()获取状态更新setDataFromPaginate()钩子,并允许我们从子组件中回调到该子组件,该子组件又将发回一个将在UserTable状态下更新的参数。 违反React的最佳做法,即通过props将原始的更新挂钩直接发送到子组件中,因此我们创建了可以调用该挂钩并传递给子组件的函数。 然后,该功能可用于回调UserTable ,并直接从使用状态更新钩UserTable

renderUserList() is a component that either renders out user cards based on either dataFromPaginate or data. If the component has just mounted, it will not have any data coming back from Paginate, so dataFromPaginate will be null. In this case, we will only render out the amount of users requested per page from our data in state. Only when Paginate has mounted and created data sets does dataFromPaginate become defined. As long as we have dataFromPaginate defined, we are rendering user pages from this. Throughout both cases, we simply loop through either data array, and return a UserCardContainer component.

renderUserList()是一个组件,可以根据dataFromPaginate或data渲染用户卡。 如果组件刚刚安装的,它不会有任何数据从美国回来Paginate ,所以dataFromPaginate将是null 。 在这种情况下,我们只会从状态数据中渲染出每页请求的用户数量。 仅当Paginate已安装并创建数据集时, dataFromPaginate定义。 只要定义了dataFromPaginate ,就可以从中渲染用户页面。 在这两种情况下,我们只循环遍历任何一个数据数组,并返回一个UserCardContainer组件。

UsersPage.js (UsersPage.js)

Honestly, there is not much to go over with this component. It is simply a container component that houses our UserTable component. There is no functionality here other than acting as a container.

老实说,这个组件没有太多要讨论的内容。 它只是容纳我们的UserTable组件的容器组件。 除了充当容器之外,这里没有其他功能。

结论 (In Conclusion)

We pass the fetched data from UserTable directly into Paginate. We give Paginate a function to update the currently rendered data set within UserTable, Paginate takes this data and determines how many pages we can make from it given how many items we want to display per page. Once it does that, it takes the data and creates an array of objects where each object key in the array is the page number, and the value is an array of items equal to the amount per page we want to show.

我们将从UserTable获取的数据直接传递给Paginate 。 我们给Paginate一个函数来更新UserTable当前呈现的数据集, Paginate接收这些数据并确定给定的每页要显示多少项,从而可以从中创建多少页。 完成此操作后,它将获取数据并创建一个对象数组,其中数组中的每个对象键都是页码,而值是一个项目数组,其值等于我们要显示的每页数量。

When a page number is selected, Paginate sends that page’s data chunk back up to the UserTable parent, where it can then be rendered. At any given time, UserTable is only rendering a chunk of data equal to the amount of items requested per page.

选择页码后, Paginate会将该页的数据块发送回UserTable父级,然后可以在其中呈现它。 在任何给定时间, UserTable仅呈现等于每页请求的项目数量的数据块。

The key here is that we are never rendering out more than amount of requested users per page. Our initial array from the API call could be 10000 users long, but if we only want to show 10 per page, we are only ever rendering that many at a time. Paginate will only ever send back the requested chunk (page) of users at a time. This allows us to pull in a large amount of data, and render it almost instantly. This is how pagination can be used to handle rendering large amounts of data, by only rendering chunks of it at a single given time.

这里的关键是,我们提供的每页请求的用户数量绝不会超过其数量。 API调用的初始数组可能是10000个用户,但是如果我们只希望每页显示10个,则一次只能渲染那么多。 Paginate只会一次发回所请求的用户块(页面)。 这使我们能够提取大量数据,并几乎立即将其呈现。 通过这种方式,可以通过仅在单个给定时间渲染大量数据来使用分页来处理大量数据。

翻译自: https://medium.com/@maison.moa/paginate-a-data-view-in-react-using-hooks-853dea8569fa

react钩子


http://www.taodudu.cc/news/show-2845361.html

相关文章:

  • Thinkphp 自动生成页码 分页显示
  • 1.6页面
  • 09-搜索前端开发-搜索页面
  • 自动化爬取新闻页面
  • 25、MySQL
  • htmlunit+quartz定时抓取博文并生成jsp页面
  • ng-alain中的st表格
  • 短网址短链接哪个好用?2021年最好的缩短链接短网址推荐
  • html5打开抖音链接,抖音主页链接在哪里弄(主页链接设置教程)
  • 我把视频变成链接_如何把长链接变成短链接?3个工具帮你实现
  • C#长链接转短链接(调用新浪api)
  • 短链接系统的设计
  • 如何利用百度短链接接口将一个长链接变成短链接
  • 3款开源软件帮你缩短链接
  • 短链接原理分析
  • 利用Python打造短链接服务
  • URL缩短器:详细说明
  • 最通俗易懂的短链接原理讲解
  • 短地址短链接免费接口:缩短链接地址。可用于缩短链接场景,如:电子发票链接,促销活动链接,新闻文章链接等
  • 淘宝京东商品长链接缩短为腾讯,新浪短链接的接口有哪些?
  • 开源 制作磁力链接_3个开源链接缩短器
  • 几个免费的长链接缩短链接工具
  • 链接太长如何缩短?稳定的短链接api接口分享与用法实例
  • Java之链接缩短
  • 2022年10个最佳URL缩短器:URL缩短器替代方案
  • sqli-labs-maser第1-6关
  • k8s-(maser节点api-server、scheduler、controller-manager.sh)
  • K8S集群扩容多master大概思路步骤
  • Elasticsearch-head-master配置 (与es连接)
  • 【复盘】记录生产环境问题,因没有及时合并maser

react钩子_使用钩子在react中分页数据视图相关推荐

  1. react钩子_了解用户的React钩子

    react钩子 Originally published at https://www.wisdomgeek.com on September 1, 2020. 最初于 2020年9月1日 在 htt ...

  2. Python基础_第5章_Python中的数据序列

    Python基础_第5章_Python中的数据序列 文章目录 Python基础_第5章_Python中的数据序列 Python中的数据序列 一.字典--Python中的==查询==神器 1.为什么需要 ...

  3. react钩子_迷上了钩子:如何使用React的useReducer()

    react钩子 So the React Conference just happened and as always something new happened. Hooks happened! ...

  4. react钩子_使用Web动画API和React钩子创建高性能动画

    react钩子 以React 挂钩方式使用Web Animations API (又名WAAPI). 让我们在现代世界中创建高性能,灵活和可操作的网络动画. 希望你们

  5. react项目_如何从零开始创建React项目(三种方式)

    在开发React项目前最关键的当然是项目的创建,现在的前端工程化使得前端项目的创建也变得越来越复杂,在这里介绍三种从零开始创建React项目的方式,分别是在浏览器中直接引入.使用官方脚手架create ...

  6. fitbit手表中文说明书_我如何分析FitBit中的数据以改善整体健康状况

    fitbit手表中文说明书 by Yash Soni 由Yash Soni 我如何分析FitBit中的数据以改善整体健康状况 (How I analyzed the data from my FitB ...

  7. 如何提取edit control中输入的数据_如何在Power Query中提取数据——列表篇(1)

    表名为列表,第一步骤名称为源 (一)从头开始提取 1. 获取列表第一个 List.First(list as list, optionaldefaultValue as any)as any 返回列表 ...

  8. Spark _25.plus _使用idea读取Hive中的数据加载成DataFrame/DataSet(四)

    对Spark _25 _读取Hive中的数据加载成DataFrame/DataSet(四) https://georgedage.blog.csdn.net/article/details/10309 ...

  9. pandas用众数填充缺失值_【机器学习】scikit-learn中的数据预处理小结(归一化、缺失值填充、离散特征编码、连续值分箱)...

    一.概述 1. 数据预处理 数据预处理是从数据中检测,修改或删除不准确或不适用于模型的记录的过程 可能面对的问题有:数据类型不同,比如有的是文字,有的是数字,有的含时间序列,有的连续,有的间断. 也可 ...

最新文章

  1. Analysis Services基础知识——深入SQL Server 2008
  2. Android Java虚拟机拦截技术分析
  3. python dataframe列数值相加,python合并dataframe中的行并将值相加
  4. oracle表格颜色,如何在oracle中使用光标更新特定颜色
  5. 设置Eclipse智能提示
  6. Javascrip—前端本地存储讲解(16)
  7. QT c++ 中使用PostMessage/SendMessage实例
  8. sign check fail: check Sign and Data Fail
  9. 大部分Java程序员都会忽略的几个问题,你中招没?
  10. centos如何使用nomachine远程连接GNOME桌面(二)
  11. oa 触发器导出流程html,哪些配套产品帮南京OA画龙点睛
  12. H3C交换机常用命令
  13. unity的UI元素层级调整的方法
  14. python批量裁剪图片_python实现图片批量剪切示例
  15. 16进制地址编码速算内存容量
  16. 树莓派如何刷RetroPie,制作一个复古游戏机
  17. iphone铃声android铃声,iphone12如何设置铃声?iphone12更换铃声方式分享[多图]
  18. 图书管理系统-数据库设计
  19. 数据外泄保护与国土安全部
  20. 破解滑块(极验)验证码思路分享

热门文章

  1. 使用机器人工具箱在matlab上进行六轴机器人(6R)运动学建模【个人简记】
  2. mockplus模板_UI设计工具比较:Sketch、Adobe XD、墨刀、Mockplus、Axure RP
  3. 前端面试官常问的问题
  4. NISP一级考试题目复习
  5. 计算机怎么更改性能模式,笔记本怎么开高性能模式 让电脑变流畅的方法详细介绍...
  6. 呼叫中心管理之:让座席看见自己
  7. 课堂笔记(常用软件,网站资源)
  8. JWT无状态登录+跨域问题
  9. Spring Boot 接口数据加解密,so easy!
  10. 2022年”泰迪杯“数据分析技能赛B题:银行客户忠诚度分析