Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of react hooks

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain the example analysis of react hooks for you in detail. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

React officially released Hooks in version 16.8. I have been following it for a long time, and recently I happen to have a small demand. Come and have a try.

Requirement description

The requirement is very simple, a data query gadget within the department. It looks like this:

When users visit the page for the first time, they will pull the data to display. Enter the filter criteria, and after clicking the query, the data will be pulled again and displayed at the front end.

Demand realization

Use React Class Component to write

If you use the previous class method, simply write it, and the code might look something like this:

Import React from 'react';import {Tabs, Input, RangeTime, Button, Table} from'. / components';class App extends React.Component {... State = {type: [], id:', title:', date: [], dataList: []} componentDidMount () {this.fetchData ();} render () {query} fetchData () {... This.setState ({dataList});} handleTypeChange () {... This.setState ({type,});} handleIdChange () {... This.setState ({id,});} handleTitleChange () {... This.setState ({title,});} handleRangeTimeChange () {... This.setState ({date,});} handleQueryBtnClick () {...}.}

Use React Hooks to write

I will not dwell on the relevant content of React hooks here. You can view the react official documentation directly and it is very well written.

Https://reactjs.org/docs/hooks-intro.html

This requirement actually has two logic: 1, input filter items. 2. Query data

A hooks on the main page, dealing with filter items and data presentation. The data request logic has a separate hooks.

Main page hooks:

Import React, {useState, useEffect} from 'react';import {Tabs, Input, RangeTime, Button, Table} from'. / components';const App = () = > {/ / data type const tabs = [{key: 1, value: 'type 1'}, {key: 0, value: 'type 2'}]; const [tab, setTab] = useState (1); / / data ID const [dataId, setDataid] = useState ('') / / title const [title, setTitle] = useState (''); / / time interval, default is one week to date const now = Date.now (); const [timeRange, setTimeRange] = useState ([now-1000 * 60 * 60 * 24 * 7, now]); / / data list const [dataList, setDataList] = useState ([]) / / Click the search button function handleBtnClick () {/ / request data.} return ID title query}

The above code completes the processing logic of the filter items. Here's how to implement the hooks. Data request.

Data request hooks:

Import React, {useState, useEffect} from 'react';import jsonp from'. / tools/jsonp';function MyFecth (url) {/ / whether const [isLoading, setIsLoanding] = useState (false) is in progress; / / request parameter const [queryParams, setQueryParams] = useState (null); / / request result const [data, setData] = useState (null) / / initiate a request to the interface const fetchData = async () = > {if (queryParams = null) {return;} setIsLoanding (true); const res = await jsonp ({url: url, data: queryParams}); setData (res); setIsLoanding (false);} / / initiate a request useEffect (() = > {fetchData ();}, [queryParams]) whenever queryParams changes / / for external calls const doGet = (params) = > {setQueryParams (params);} return {isLoading, data, doGet}} export default MyFecth

On the main page, the reference data request hooks:

Import React, {useState, useEffect} from 'react';import {Tabs, Input, RangeTime, Button, Table} from'. / components';import MyFecth from'. / MyFetch';const App = () = > {/ / ① use data request hooks const {isLoading, data, doGet} = MyFecth ('http://xxx'); / / data type const tabs = [{key: 1, value:' type 1'}, {key: 0, value: 'type 2'}] Const [tab, setTab] = useState (1); / / data ID const [dataId, setDataid] = useState (''); / / title const [title, setTitle] = useState (''); / / time range, default is one week to date const now = Date.now (); const [timeRange, setTimeRange] = useState ([now-1000 * 60 * 60 * 24 * 7, now]); / / data list const [dataList, setDataList] = useState ([]) / / Click the search button function handleBtnClick () {/ / ② and click the button to request data const params = {}; title & & (params.title = title); dataId & & (params.dataId = dataId); params.startTime = String (timeRange [0]); params.endTime = String (timeRange [1]); doGet (params);} / / after the ③ data changes, render the list again. / / this is equivalent to componentDidUpdate. When data changes, re-render the page useEffect (() = > {setDataList (data);}, [data]); / / when ④ enters the page for the first time, there are no filter entries. Pull the data and render the page. / / the second parameter of useEffect is an empty array, which is equivalent to executing the "side effect" useEffect (() = > {doGet ({});}, []) during componentDidMount; return ID header query}

Some thoughts on React Hooks

When you finish writing this requirement with hooks, the most intuitive feeling is that the code is easy to write. You don't need to write a lot of setState as before. The second is

Hooks's api is so well designed that a useState can pair [state] with [logic to change state]. The basic idea of React is [data-to-view mapping]. In hooks, useEffect is used to indicate the [side effects]. It feels that react officials also tend to make no distinction between componentDidMount and componentDidUpdate.

As can be seen from the api design, hooks advocates fine-grained splitting of component states. In a hooks component, there may be a lot of states. If some actions of the user need to modify both states at the same time, then I need to call the modification logic of these two states respectively, which will cause the component to be re-render twice. In components that use class writing, you only need to setState once. From this point of view, the operation of render twice in hooks may bring some performance problems? This requires us to be thoughtful and abstract when designing component structure and state.

This is the end of this article on "sample Analysis of react hooks". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report