preface

React Hook has been out for a long time, but I didn’t get to know it before. Recently, I spent some time to look at it, and I am still impressed by it. It has been a long time since React was developed. However, for some components of the same logic processing, has been done not quite in place, so always write a lot of repeated code in similar components, so when looking at hookAPI is also with the past thinking and review, hoping to find a good solution.

Leaving aside the basic API, the best way to learn something is to read the official documentation carefully, so I’ll jump right into the text.

Write a paged table using the Class component

To encapsulate the API layer



The class component declares state (typically there is also a params parameter to indicate the table query parameter omitted in the screenshot).



Class component to write request methods



Class component to write paging methods

In the development of business systems, every page, always repeat to write these codes, these methods keep copying and pasting, this is probably the so-called copy engineer.

Rewrite the paging table using hook

Start by thinking about what states are generally required for paged tables

  1. The number of pages displayed on the current page and on a page
  2. The total number of pieces of data
  3. Return table data data
  4. Data loading state load

Define a custom hook to do all the logic in this custom hook



Use useState to define state for paging and total entries

Use the useCallback function to return the cached page handling function



UseCallback is executed when the function component is first rendered, and then again when its dependent variable changes. I don’t need to repeat this, so I pass a [];

Write the logic to send the request using the hook used by the handler

UseEffect is used specifically for side effects. By default, it is performed when a function component is rendered for the first time, and subsequent executions are performed when dependent variables change. Table data changes are usually requested again when the page bar changes or search parameters change, so the dependency array should be added with [page,parms].

OK basic logic is written at the end

return { page, load, changePage, tableData, total };
Copy the code

Finally, you pass in the API method in the component using a custom hook that you have written



This way we only need to reference our custom hooks in our component.