Home > Article > Web Front-end > 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.
Application Employees.org
Do two things:
1. Get 20
employees as soon as you enter the program.
2. You can filter employees by filtering conditions.
Before implementing these two requirements, let’s review the 2
life cycle methods of React class components:
componentDidMount()
: Executed after the component is mounted componentDidUpdate(prevProps)
: When props
or state
Executed when changedComponent<employeespage></employeespage>
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 <div>获取员工数据中...</div>; } return <EmployeesList employees={employees} />; } }
OpencodesandboxYou can view the <employeespage></employeespage>
acquisition process.
<employeespage></employeespage>
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.
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 <employeespage></employeespage>
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 <div>Fetching employees....</div>; } return <EmployeesList employees={employees} />; }
Open codesandboxYou can view useEffect()
how to obtain data.
You can see that using Hooks <employeespage></employeespage>
is much simpler than using class components.
In <employeespage></employeespage>
useEffect(fetch, [query])
in the <employeespage></employeespage>
function component, execute the fetch
callback after the initial rendering. In addition, the fetch
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: <pre class="brush:js;toolbar:false;">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} />;
}</pre>
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
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 处于试验阶段。
<suspense></suspense>
包装执行异步操作的组件:
<Suspense fallback={<span>Fetch in progress...</span>}> <FetchSomething /> </Suspense>
数据获取时,Suspense
将显示fallback
中的内容,当获取完数据后,Suspense
将使用获取到数据渲染<fetchsomething></fetchsomething>
。
来看看怎么使用Suspense
:
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} />; }
打开codesandbox可以查看Suspense
如何获取数据。
<employeespage></employeespage>
使用Suspense
处理组件将获取到数据传递给<employeesfetch></employeesfetch>
组件。
<employeesfetch></employeesfetch>
中的resource.employees
是一个特殊包装的promise
,它在背后与Suspense
进行通信。这样,Suspense
就知道“挂起” <employeesfetch></employeesfetch>
的渲染要花多长时间,并且当资源准备就绪时,就开始执行渲染工作。
最大的优点是: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!