React模式:集中式PropTypes

通过集中化PropType避免重复自己 (Avoid repeating yourself by centralizing PropTypes)

There are three popular ways to handle types in React: PropTypes, TypeScript and Flow. This post is about PropTypes, which are currently the most popular.

在React中有三种流行的处理类型的方法: PropTypesTypeScriptFlow 。 这篇文章是关于PropTypes的,这是目前最受欢迎的。

Since PropTypes provide type warnings at runtime, it’s helpful to be as specific as possible.

由于PropTypes在运行时提供类型警告,因此尽可能具体是有帮助的。

  • Component accepts an object? Declare the object’s shape.

    组件接受一个对象? 声明对象的形状。
  • Prop only accepts a specific list of values? Use oneOf.

    道具只接受特定的值列表? 使用oneOf。
  • Array should contain numbers? Use arrayOf.

    数组应该包含数字? 使用arrayOf。
  • You can even declare your own types. AirBnB offers many additional PropTypes.

    您甚至可以声明自己的类型。 AirBnB提供了许多其他PropType

Here’s a PropType example:

这是一个PropType示例:

UserDetails.propTypes = {
 user: PropTypes.shape({
   id: PropTypes.number.isRequired,
   firstName: PropTypes.string.isRequired,
   lastName: PropTypes.string.isRequired,
   role: PropTypes.oneOf(['user','admin'])
};

In real apps with large objects, this quickly leads to a lot of code. That’s a problem, because in React, you’ll often pass the same object to multiple components. Repeating these details in multiple component files breaks the DRY principle (don’t repeat yourself). Repeating yourself creates a maintenance problem.

在带有大型对象的实际应用中,这很快会导致大量代码。 这是一个问题,因为在React中,您通常会将同一对象传递给多个组件 。 在多个组件文件中重复这些详细信息会破坏DRY原理 (请不要重复自己)。 重复自己会造成维护问题。

The solution? Centralize your PropTypes.

解决方案? 集中您的PropTypes

这是集中PropType的方法 (Here’s How to Centralize PropTypes)

I prefer centralizing PropTypes in /types/index.js.

我更喜欢将PropTypes集中在/types/index.js中。

I’m using named imports on line 2 to shorten the declarations. ?

我在第2行上使用命名导入来缩短声明。 ?

And here’s how I use the PropType I declared above:

这就是我使用上面声明的PropType的方式:

// types/index.js
import { shape, number, string, oneOf } from 'prop-types';

export const userType = shape({
  id: number,
  firstName: string.isRequired,
  lastName: string.isRequired,
  company: string,
  role: oneOf(['user', 'author']),
  address: shape({
    id: number.isRequired,
    street: string.isRequired,
    street2: string,
    city: string.isRequired,
    state: string.isRequired,
    postal: number.isRequired
  });
});

I use a named import to get a reference to the exported PropType declaration on line 2. And I put it to use on line 13.

我使用命名导入在第2行上获取对导出的PropType声明的引用,并在第13行上使用它。

Benefits:

好处

  1. The centralized PropType radically simplifies the component’s PropType declaration. Line 13 just references the centralized PropType, so it’s easy to read.

    集中式PropType从根本上简化了组件的PropType声明。 第13行仅引用集中的PropType,因此很容易阅读。
  2. The centralized type only declares the shape, so you can still mark the prop as required as needed.

    集中式仅声明形状,因此您仍可以根据需要标记道具。
  3. No more copy/paste. If the object shape changes later, you have a single place to update. ?

    没有更多的复制/粘贴。 如果对象形状稍后更改,则可以在一个位置进行更新。 ?

Here’s a working example on CodeSandbox.

这是CodeSandbox上的一个工作示例

额外的功劳:生成您的道具类型 (Extra Credit: Generate Your PropTypes)

Finally, consider writing some custom code to generate your PropType declarations from your server-side code. For example, if your API is written using a strongly typed language like C# or Java, consider generating your PropType declarations as part of your server-side API build process by reading the shape of your server-side classes. This way you don’t have to worry about keeping your client-side PropTypes and your server-side API code in sync. ?

最后,考虑编写一些自定义代码,以根据服务器端代码生成PropType声明。 例如,如果您的API是使用诸如C#或Java之类的强类型语言编写的,则可以考虑通过读取服务器端类的形状来生成PropType声明,作为服务器端API构建过程的一部分。 这样,您不必担心保持客户端PropType和服务器端API代码同步。 ?

Side-note: If you know of a project that does this for any server-side languages, please reply in the comments and I’ll add a link here.

旁注 :如果您知道一个针对任何服务器端语言执行此操作的项目,请在评论中进行回复,我将在此处添加一个链接。

Edit: You can convert JSON into PropTypes using transform.now.sh. ?

编辑 :您可以使用transform.now.sh将JSON转换为PropTypes。 ?

摘要 (Summary)

  1. Declare your PropTypes as explicitly as possible, so you know when you’ve made a mistake.

    尽可能明确地声明您的PropType,以便您知道犯错的时间。
  2. Centralize your PropTypes to avoid repeating yourself.

    集中化您的PropType,以避免重复您自己。
  3. If you’re working in a strongly typed language on the server, consider generating your PropTypes by reading your server-side code. This assures your PropTypes match your server-side types.

    如果您在服务器上使用强类型语言,请考虑通过阅读服务器端代码来生成PropType。 这样可以确保您的PropTypes与服务器端类型匹配。

寻找更多关于React的信息? ⚛️ (Looking for More on React? ⚛️)

I’ve authored multiple React and JavaScript courses on Pluralsight (free trial).

我已经在Pluralsight上编写了多个React和JavaScript课程 ( 免费试用 )。

Cory House is the author of multiple courses on JavaScript, React, clean code, .NET, and more on Pluralsight. He is principal consultant at reactjsconsulting.com, a Software Architect at VinSolutions, a Microsoft MVP, and trains software developers internationally on software practices like front-end development and clean coding. Cory tweets about JavaScript and front-end development on Twitter as @housecor.

Cory HouseJavaScript,React,干净代码,.NET等课程多本课程的作者,并且还提供了有关Pluralsight的更多课程 。 他是reactjsconsulting.com的首席顾问, VinSolutions的软件架构师,Microsoft MVP,并且在软件开发方面对国际软件开发人员进行了培训,例如前端开发和简洁编码。 Cory在Twitter上以@housecor表示关于JavaScript和前端开发的推

翻译自: https://www.freecodecamp.org/news/react-pattern-centralized-proptypes-f981ff672f3b/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值