Home > Web Front-end > JS Tutorial > body text

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

青灯夜游
Release: 2020-08-04 17:10:44
forward
1890 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, and Suspense are 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

Application Employees.orgDo two things:

1. Get 20 employees 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 the 2 life cycle methods of React class components:

  1. componentDidMount(): Executed after the component is mounted
  2. componentDidUpdate(prevProps): When props or state Executed 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 the acquisition process.

There is an asynchronous method to get data fetch(). After the get request completes, use the setState method to update employees.

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

When our keywords are filtered, props.query will be updated. Whenever props.query is updated, componentDidUpdate() will be re-executed this.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, And componentDidUpdate() re-obtains data when props is updated.

Disadvantages

Boilerplate code

Class-based components require Inherit React.Component, execute super(props) in the constructor, etc.

this

Using the this keyword is troublesome.

Code duplication

componentDidMount()The code in componentDidUpdate() 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 recall useEffect(callback[, deps]) Hook. This hook executes callback after mounting, and re-renders when dependencies deps change.

As shown in the following example, use useEffect() in to 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

Open codesandboxYou can view useEffect()how to obtain data.

You can see that using Hooks is much simpler than using class components.

In useEffect(fetch, [query]) in the function component, execute the fetch callback after the initial rendering. In addition, the fetch method
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 'react';

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 
Fetching employees....
; } return ; }
Copy after login
Mention the required value from useEmployeesFetch(). 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
Popular Tutorials
More>
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!