Which method is more suitable for data acquisition in the React?

Author: Dmitri Pavlutin
Translator: small-dimensional FE
Original: dmitripavlutin.com

Foreign article, the author uses paraphrase way to ensure the readability of the article.

When performing such image data acquisition I / O operations, you must initiate an acquisition request, waits for a response, the response component to save state data, the final rendering. Asynchronous data acquisition will require additional work to adapt the declarative React, React has gradually improved to minimize this extra work. Lifecycle functions, hooks and suspense are React the way to get data, I will discuss their advantages and disadvantages, respectively, in the following example. Only by understanding the specifics of each mode in order to help you better achieve asynchronous operation in the code.

1. Use the function to get the data life cycle

The following applications must do two things:

(1) initialization obtain 20 employees of the company;

(2) filter out employees names that contain query.

Before implementing these requirements, review the two components of the life-cycle approach class:

(1) componentDidMount(): after performing a mount assembly;

(2) componentDidUpdate(prevProps): When propsand stateexecution time changes.
<EmployeesPage>Using these two functions to achieve the life cycle of the data 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 <div>Fetching employees....</div>;
    }
    return <EmployeesList employees={employees} />;
  }
}

Open example to explore <EmployeesPage>how to get the data. <EmployeesPage>There is an asynchronous fetchmethod used to obtain the data, when acquired accomplished using the acquired employeesupdate the status of the components. this.fetch()In componentDidMount()the implementation life cycle functions: start obtaining employee data when the component initialization rendering is complete.
When the user enters a query in the input box, queryproperty changes occur, each time when it changes, this.fetch()both will componentDidUpdateperform lifecycle functions, thus to achieve employee screening function. Although the life-cycle approach is relatively easy to grasp, but there is boilerplate code reusability and difficulty based on class.

Pros:
Easy. Relatively easy to understand: life-cycle method componentDidMountinitiates a request to obtain data after the first rendering component initialization, when propsby the time changes componentDidUpdateretrieve data.

Disadvantages:

(1) boilerplate code. Have "a sense of ceremony" component-based code like: inheritance React.Component, and need to constructorcall super(props), and so on;

(2) this problem. Use this keyword a lot of trouble;

(3) code is repeated. In componentDidMountand componentDidUpdatethe code in fact most of them are repetitive;

(4) it is difficult to reuse. Gets the logical employees if it is in other components it has been difficult to re-use.

2. Use the hooks to get data

For class-based component is, hooks is a better choice. As an ordinary function is concerned, hooks codes have abandoned the "sense of ritual" and easier to reuse.
We first look at useEffect(callback[, deps])the use of the hook function. The hooking function executes in the mounted assembly callback, when the dependency depsafter the change will continue to perform the subsequent rendering. In the following examples <EmployeesPage>use useEffect()to obtain employee data:

import React, { useState } from 'react';

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 <div>Fetching employees....</div>;
  }
  return <EmployeesList employees={employees} />;
}

Open example to look at useEffect()is how to get the data. You can see the use useEffect()of version than the class of the component is much simplified. In the EmployeesPagefunctional components useEffect(fetch, [query])is performed after the first rendering component fetchcallback, and only queryafter the property changes, the components will be performed again after re-rendering fetchcallback. But we still have room for improvement, hooks allow you to get the logical staff from <EmployeesPage>extracted, we'll try:

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 <div>Fetching employees....</div>;
  }
  return <EmployeesList employees={employees} />;
}

Our data acquisition logic has been extracted useEmployeesFetch()in the. Component <EmployeesPage>has not integrated any relevant data acquisition logic, but rather focus on his most direct job: UI rendering. More important is that you can reuse in any of the components required to obtain employee data useEmployeesFetch().
advantage

(1) simple and clear. hooks boilerplate code is not binding as they are simply normal function;

(2) reusability. hooks implemented in data acquisition logic is easily multiplexed.
Shortcoming

(1) entry barriers. hooks a little counterintuitive, you have to understand them before using, hooks rely closures , so you will also need to clarify them.

(2) imperative. Use hooks, you still need to use the command-style way to perform data acquisition.

3. Use the suspense obtain data

suspense provide a declarative way to get data asynchronously in React.
<Suspense>Performing a packaging assembly asynchronous operation:

<Suspense fallback={<span>Fetch in progress...</span>}>
  <FetchSomething />
</Suspense>

When is acquiring data, suspense will render fallbackcontent properties. When the data acquisition is completed, suspense the acquired data will be used to render the <FetchSomething />assembly. Let's see how employees will use suspense to the application:

import React, { Suspense } from "react";
import EmployeesList from "./EmployeesList";

function EmployeesPage({ resource }) {
  return (
    <Suspense fallback={<h1>Fetching employees....</h1>}>
      <EmployeesFetch resource={resource} />
    </Suspense>
  );
}

function EmployeesFetch({ resource }) {
  const employees = resource.employees.read();
  return <EmployeesList employees={employees} />;
}

Open example to check how suspense works. <EmployeesPage>Suspense processing components for use <EmployeesFetch>in the data acquisition logic. <EmployeesFetch>The resource.employeesit is a special wrapped promise to communicate in the background and suspense, this way you can know in suspense <EmployeesFetch>before being rendered to pause long, and know when the resources in place to continue rendering.

Maximum highlights: Suspense uses a declarative manner and process of synchronizing asynchronous operation.

These components integrate itself does not get any data relevant details, instead they declaratively using the resource to render content. No life-cycle function, no hooks, no async / await, nor in the callback internal components: just rendering resources.
Advantages :

(1) declarative. suspense allows you to perform asynchronous operations React to declarative way;

(2) simple and clear. Declarative code to use more simple, component itself is not concerned with the details of data acquisition;

(3) the acquisition logic loose coupling. Because the component uses suspense itself does not know how to get the data: it uses REST or GraphQL. The details of one suspense set boundaries for protecting the data acquired from leaking to the internal components;

(4) no race condition. If both open multiple asynchronous operations acquired, suspense with the most recent acquisition request.
Drawback :
the need adapters. suspense need has achieved its professional fetching fetching interface library or adapter.

4. Summary

Life Cycle function once for a long time is the only means of data acquisition. However, will bring a lot of problems such as a large amount of boilerplate code in this way, repeat and reuse difficult. The use hooks to retrieve data is a better choice: we have reduced a lot of boilerplate code. Benefits suspense is declarative access to data, you do not care about the details of the component itself acquired data, while suspense is the closest React itself declarative ideas.

Which way to get the data you prefer it?

Original: https://dmitripavlutin.com/react-fetch-lifecycle-methods-hooks-suspense/

5. AC

Today, the main way React share of several data acquisition and comparison of the advantages and disadvantages of each approach, aimed at so that we can be more handy in asynchronous operation, and we hope to discuss with each other technology, can talk about.

The article has been updated to synchronize Github blog , if the article can still feel, feel free to star!

One of your thumbs, so I deserve more effort!

The face of adversity to grow, and only continue to learn in order to become better themselves, and the king of mutual encouragement!

Guess you like

Origin www.cnblogs.com/tangshiwei/p/11819369.html