react中的高阶组件_现实生活中的React高阶组件用例(withLoading)

react中的高阶组件

Higher Order Components in React are considered an advanced React topic. I will try to simplify it and show one real life example that we will hopefully use (or base on it) in real life.

React中的高阶组件被视为高级React主题。 我将尝试简化它,并显示一个现实生活中的示例,希望我们在现实生活中使用(或基于它)。

Let’s consider our day to day task which is to fetch data from somewhere and display them in the UI. We also need to handle errors and show loader messages to the user. This article will focus on the loader component.

让我们考虑我们的日常任务,该任务是从某处获取数据并将其显示在UI中。 我们还需要处理错误并向用户显示加载程序消息。 本文将重点介绍加载程序组件。

For the sake of this exercise we will consider two approaches:

为了进行此练习,我们将考虑两种方法:

  • in the first approach we will handle loader in the component

    在第一种方法中,我们将处理组件中的加载程序
  • in the second approach we will use Higher Order Component

    在第二种方法中,我们将使用高阶分量

You can see the example code in the sandbox and here is the GitHub repository.

您可以在沙箱中看到示例代码,这是GitHub存储库。

第一件事 (First things first)

Let’s create a new React app with:

让我们创建一个新的React应用程序:

npx create-react-app hoc-demo

npx create-react-app hoc-demo

Then we can open our IDE and start the terminal.

然后,我们可以打开IDE并启动终端。

清单组件 (List component)

Our <List/> component looks similar to below:

我们的<List/>组件类似于以下内容:

import React from "react";
export const List = ({ data }) => { if (!data) return null; if (!data.length) return <p>No data</p>; return ( <ul> {data.map((item) => { return <li key={item.id}>{item.name}</li>; })} </ul> );};

We have basic error handling in here which should cover most of the cases:

在这里,我们有基本的错误处理,其中应涵盖大多数情况:

if (!data) return null;if (!data.length) return <p>No data, sorry</p>;

Going forward at this point we are sure that we have some data in our data array. We can proceed with basic HTML list to display the data:

在这一点上,我们确定data数组中有一些数据。 我们可以继续使用基本HTML列表来显示数据:

return (  <ul>    {data.map((item) => {      return <li key={item.id}>{item.full_name}</li>;     })}  </ul>);

装载机组件 (Loader Component)

It’s a very simple component to be shown when we fetch the data.

这是我们获取数据时要显示的非常简单的组件。

import React from "react";export const Loader = () => {  return <p>Fetching the data</p>;};

处理组件中的加载程序状态 (Handling loader state in the component)

One of the popular approaches is to handle loading states directly in the component i.e.

一种流行的方法是直接在组件中处理加载状态,即

import React from "react";
import { Loader, List } from 'components';const ExampleComponent = ({ data, isLoading }) => { return isLoading ? <Loader/> : <List data={data} />;};

This is very simple solution utilising ternary operator. It works, is battle proven and sometimes it’s exactly what we need.

这是利用三元运算符的非常简单的解决方案。 它有效,经战斗证明,有时正是我们需要的。

It does not however scale very well if we need similar behaviour in lot’s of different places.

但是,如果我们在许多不同的地方需要类似的行为,它的伸缩性就不会很好。

To counter that we can introduce Higher Order Component pattern.

为了解决这个问题,我们可以引入高阶组件模式。

加载高阶组件 (withLoading Higher Order Component)

For the sake of this exercise our Higher Order Component is very basic so that we get the feeling of it:

为了进行此练习,我们的高阶组件非常基础,因此我们可以体会到:

import React from "react";/*** HOC to handle loading states.* Returns passed component or loader component/message** @param  {*} Component*             Component to be displayed if the loading is finished** @return {*} Component to be displayed or loading message   **/function WithLoading(Component) {  return function WithLoadingComponent({ isLoading, ...props }) {    if (!isLoading) return <Component {...props} />;       return <p>Fetching data...</p>;    };}export default WithLoading;

We can then use it:

然后我们可以使用它:

import React from "react";
import { List } from 'components';
import WithLoading from "hoc";// calling our HOCconst ListWithLoading = WithLoading(List);const ExampleComponent = ({ data, isLoading }) => { return <ListWithLoading isLoading={isLoading} data={data} />;};

Now we no longer have to worry about conditionally handling loader in the component. This part of the code is definitely reusable.

现在,我们不再需要担心在组件中有条件地处理加载程序。 这部分代码肯定是可重用的。

We could extend our HoC to handle custom loading message with help of a parameter i.e.

我们可以扩展HoC以借助参数来处理自定义加载消息,即

import React from "react";import { Loader } from "components";/*** HOC to handle loading states.* Returns passed component or loader component/message* * @param  {*} Component*             Component to be displayed if the loading is finished** @param  {*} LoaderComponent*             Component to be displayed during data fetching*             Defaults to Loader component* @return {*} Component to be displayed or loader component**/function WithLoading(Component, LoaderComponent = Loader) {  return function WithLoadingComponent({ isLoading, ...props }) {    if (!isLoading) return <Component {...props} />;      return <LoaderComponent {...props} />;    };   }export default WithLoading;

Now we can call it like so:

现在我们可以这样称呼它:

const ListWithLoading = WithLoading(List, CustomLoaderComponent);

or just

要不就

const ListWithLoading = WithLoading(List);

and the <Loader/> component would be used as a default one if second parameter is omitted.

如果省略第二个参数,则<Loader/>组件将用作默认组件。

This solution scales really well.

该解决方案的扩展性非常好。

摘要 (Summary)

In this article I’ve presented basic, battle proven and justified use case of React HOC — withLoading.

在本文中,我介绍了React HOC的基本,经过withLoading和合理的用例— withLoading

Another interesting use case might be withAuthcomponent where we would protect our components based on some isAuthenticatedvalue. That is a topic for another discussion however. :) In my opinion, the HOC are not very advanced topic and definitely have useful use cases. It’s just they are often overengineered and misunderstood by the developers.

另一个有趣的用例可能是withAuth组件,其中我们将基于某些isAuthenticated值来保护我们的组件。 但是,这是另一个讨论的主题。 :)我认为,HOC并不是一个非常高级的主题,肯定有有用的用例。 只是它们经常被开发人员过度设计和误解。

Just keep it simple and don’t create one for the sole purpose of creating one. You will know it when you need one.

只要保持简单,就不要仅仅为了创建一个而创建一个。 您将在需要时知道它。

翻译自: https://medium.com/@tymekluczko/real-life-react-higher-order-component-use-case-withloading-ff0a4027089a

react中的高阶组件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值