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.
ApplicationEmployees.org
Do two things:
1. Get20
employees as soon as you enter the program.
2. You can filter employees by filtering conditions.
Before implementing these two requirements, let’s review the2
life cycle methods of React class components:
componentDidMount()
: Executed after the component is mountedcomponentDidUpdate(prevProps)
: Whenprops
orstate
Executed when changedComponent
Use 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; } }
OpencodesandboxYou can view the
acquisition process.
There is an asynchronous method to get datafetch()
. After the get request completes, use thesetState
method 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.query
will be updated. Wheneverprops.query
is 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 whenprops
is updated.
Disadvantages
Boilerplate code
Class-based components require InheritReact.Component
, executesuper(props)
in the constructor, etc.
this
Using thethis
keyword 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.
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 executescallback
after mounting, and re-renders when dependenciesdeps
change.
As shown in the following example, useuseEffect()
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) { returnFetching employees....; } return; }
OpencodesandboxYou can viewuseEffect()
how to obtain data.
You can see that using Hooks
is much simpler than using class components.
InuseEffect(fetch, [query])
in the
function component, execute thefetch
callback after the initial rendering. In addition, thefetch
method
will also be re-executed when the dependency
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:
Mention the required value fromimport 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} />; }
useEmployeesFetch()
. Component
has no corresponding acquisition logic and is only responsible for rendering the interface.Even better, you can reuse
Advantages
Clear and SimpleHooks have no boilerplate code because they are ordinary functions.
ReusabilityRequires 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,仍然必须使用命令式方法来执行数据获取。
Suspense
提供了一种声明性方法来异步获取React中的数据。
注意:截至2019年11月,Suspense 处于试验阶段。
包装执行异步操作的组件:
Fetch in progress...}>
数据获取时,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; }
打开codesandbox可以查看Suspense
如何获取数据。
使用Suspense
处理组件将获取到数据传递给
组件。
中的resource.employees
是一个特殊包装的promise
,它在背后与Suspense
进行通信。这样,Suspense
就知道“挂起”
的渲染要花多长时间,并且当资源准备就绪时,就开始执行渲染工作。
最大的优点是:Suspense
以声明性和同步的方式处理异步操作。组件没有复杂数据获取逻辑,而是以声明方式使用资源来渲染内容。在组件内部没有生命周期,没有 Hooks,async/await
,没有回调:仅展示界面。
声明式
Suspense
以声明的方式在React中执行异步操作。
简单
声明性代码使用起来很简单,这些组件没有复杂的数据获取逻辑。
松耦合与获取实现
使用Suspense
的组件看不出如何获取数据:使用 REST 或 GraphQL。Suspense
设置一个边界,保护获取细节泄露到组件中。
如果请求了多个获取操作,那么Suspense
会使用最新的获取请求。
原文:https://dmitripavlutin.com/re...
很长一段时间以来,生命周期方法一直是获取数据方式的唯一解决方案。然而,使用它们获取数据会有很多样板代码、重复和可重用性方面的问题。
使用 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!