A brief discussion on the methods of obtaining data in React and their advantages and disadvantages

青灯夜游
Release: 2020-08-04 17:10:44
forward
1976 people have browsed it

A brief discussion on the methods of obtaining data in React and their advantages and disadvantages

When performing I/O operations (such as data extraction), you must first send a network request, then wait for the response, then save the response data to the component's state, and finally render.

In React,lifecycle methods,Hooks, andSuspenseare methods for obtaining data. Next, we will use examples to demonstrate how to use them and explain the advantages and disadvantages of each method so that we can better write asynchronous operation code.

1. Request data using life cycle methods

ApplicationEmployees.orgDo two things:

1. Get20employees as soon as you enter the program.
2. You can filter employees by filtering conditions.

A brief discussion on the methods of obtaining data in React and their advantages and disadvantages

Before implementing these two requirements, let’s review the2life cycle methods of React class components:

  1. componentDidMount(): Executed after the component is mounted
  2. componentDidUpdate(prevProps): WhenpropsorstateExecuted when changed

ComponentUse the above two life cycle methods to implement the acquisition logic:

import EmployeesList from "./EmployeesList"; import { fetchEmployees } from "./fake-fetch"; class EmployeesPage extends Component { constructor(props) { super(props); this.state = { employees: [], isFetching: true }; } componentDidMount() { this.fetch(); } componentDidUpdate(prevProps) { if (prevProps.query !== this.props.query) { this.fetch(); } } async fetch() { this.setState({ isFetching: true }); const employees = await fetchEmployees(this.props.query); this.setState({ employees, isFetching: false }); } render() { const { isFetching, employees } = this.state; if (isFetching) { return 
获取员工数据中...
; } return ; } }
Copy after login

OpencodesandboxYou can view theacquisition process.

There is an asynchronous method to get datafetch(). After the get request completes, use thesetStatemethod to updateemployees.

this.fetch()Executed in thecomponentDidMount()life cycle method: it gets the employee data when the component is initially rendered.

When our keywords are filtered,props.querywill be updated. Wheneverprops.queryis updated,componentDidUpdate()will be re-executedthis.fetch().

While lifecycle methods are relatively easy to master, class-based methods have boilerplate code that makes reusability difficult.

Advantages

This method is easy to understand:componentDidMount()Get the data on the first rendering, AndcomponentDidUpdate()re-obtains data whenpropsis updated.

Disadvantages

Boilerplate code

Class-based components require InheritReact.Component, executesuper(props)in the constructor, etc.

this

Using thethiskeyword is troublesome.

Code duplication

componentDidMount()The code incomponentDidUpdate()is mostly repeated.

Difficult to reuse

The employee acquisition logic is difficult to reuse in another component.

2. Use Hooks to obtain data

Hooks is a better choice for obtaining data based on classes. As simple functions, Hooks do not need to be inherited like class components and are easier to reuse.

Briefly recalluseEffect(callback[, deps])Hook. This hook executescallbackafter mounting, and re-renders when dependenciesdepschange.

As shown in the following example, useuseEffect()into obtain employee data:

import EmployeesList from "./EmployeesList"; import { fetchEmployees } from "./fake-fetch"; function EmployeesPage({ query }) { const [isFetching, setFetching] = useState(false); const [employees, setEmployees] = useState([]); useEffect(function fetch() { (async function() { setFetching(true); setEmployees(await fetchEmployees(query)); setFetching(false); })(); }, [query]); if (isFetching) { return 
Fetching employees....
; } return ; }
Copy after login

OpencodesandboxYou can viewuseEffect()how to obtain data.

You can see that using Hooksis much simpler than using class components.

InuseEffect(fetch, [query])in thefunction component, execute thefetchcallback after the initial rendering. In addition, thefetchmethod
will also be re-executed when the dependency

query

is updated.But there is still room for optimization. Hooks allow us to extract employee retrieval logic from the

component. Let’s take a look:

import React, { useState } from &#39;react&#39;; import EmployeesList from "./EmployeesList"; import { fetchEmployees } from "./fake-fetch"; function useEmployeesFetch(query) { // 这行有变化 const [isFetching, setFetching] = useState(false); const [employees, setEmployees] = useState([]); useEffect(function fetch { (async function() { setFetching(true); setEmployees(await fetchEmployees(query)); setFetching(false); })(); }, [query]); return [isFetching, employees]; } function EmployeesPage({ query }) { const [employees, isFetching] = useEmployeesFetch(query); // 这行有变化 if (isFetching) { return <div>Fetching employees....</div>; } return <EmployeesList employees={employees} />; }
Copy after login
Mention the required value fromuseEmployeesFetch(). Component

has no corresponding acquisition logic and is only responsible for rendering the interface.Even better, you can reuse

useEmployeesFetch()

in any other component that needs to get employees.

Advantages

Clear and Simple

Hooks have no boilerplate code because they are ordinary functions.

Reusability

The data acquisition logic implemented in Hooks is easy to reuse.

Disadvantages

Requires prior knowledge

###Hooks are a bit counterintuitive, so you must understand them before using them, Hooks rely on closures, so be sure to understand them well . ###

必要性

使用Hooks,仍然必须使用命令式方法来执行数据获取。

3.使用 suspense 获取数据

Suspense提供了一种声明性方法来异步获取React中的数据。

注意:截至2019年11月,Suspense 处于试验阶段。

包装执行异步操作的组件:

Fetch in progress...}>  
Copy after login

数据获取时,Suspense将显示fallback中的内容,当获取完数据后,Suspense将使用获取到数据渲染

来看看怎么使用Suspense

import React, { Suspense } from "react"; import EmployeesList from "./EmployeesList"; function EmployeesPage({ resource }) { return ( Fetching employees....}>   ); } function EmployeesFetch({ resource }) { const employees = resource.employees.read(); return ; }
Copy after login

打开codesandbox可以查看Suspense如何获取数据。

使用Suspense处理组件将获取到数据传递给组件。

中的resource.employees是一个特殊包装的promise,它在背后与Suspense进行通信。这样,Suspense就知道“挂起”的渲染要花多长时间,并且当资源准备就绪时,就开始执行渲染工作。

最大的优点是:Suspense以声明性和同步的方式处理异步操作。组件没有复杂数据获取逻辑,而是以声明方式使用资源来渲染内容。在组件内部没有生命周期,没有 Hooks,async/await,没有回调:仅展示界面。

优点

声明式

Suspense以声明的方式在React中执行异步操作。

简单

声明性代码使用起来很简单,这些组件没有复杂的数据获取逻辑。

松耦合与获取实现

使用Suspense的组件看不出如何获取数据:使用 REST 或 GraphQL。Suspense设置一个边界,保护获取细节泄露到组件中。

标准状态

如果请求了多个获取操作,那么Suspense会使用最新的获取请求。

原文:https://dmitripavlutin.com/re...

4.总结

很长一段时间以来,生命周期方法一直是获取数据方式的唯一解决方案。然而,使用它们获取数据会有很多样板代码、重复和可重用性方面的问题。

使用 Hooks 获取数据是更好的选择:更少的样板代码。

Suspense的好处是声明性获取。咱们的组件不会被获取实现细节弄得乱七八糟。Suspense更接近于React本身的声明性本质。

英文原文地址:https://dmitripavlutin.com/react-fetch-lifecycle-methods-hooks-suspense/

为了保证的可读性,本文采用意译而非直译。

更多编程相关内容,请关注php中文网编程入门栏目!

The above is the detailed content of A brief discussion on the methods of obtaining data in React and their advantages and disadvantages. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!