当前位置: 首页 > 编程日记 > 正文

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中有三种流行的处理类型的方法: PropTypes , TypeScript和Flow 。 这篇文章是关于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 House是JavaScript,React,干净代码,.NET等课程的多本课程的作者,并且还提供了有关Pluralsight的更多课程 。 他是reactjsconsulting.com的首席顾问, VinSolutions的软件架构师,Microsoft MVP,并且在软件开发方面对国际软件开发人员进行了培训,例如前端开发和简洁编码。 Cory在Twitter上以@housecor表示关于JavaScript和前端开发的推文 。

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

相关文章:

Java Class SecurityManager

# 前言 简单了解 SecurityManager。具体查阅 API。 # What 它是 Java 沙盒模型控制安全的重要一个环节。它是 Java 的一个类。下面一段话源于SecurityManager API: The security manager is a class that allows applications to implement a security policy. It a…

微信小程序,对象转换成数组

有问题可以扫码加我微信,有偿解决问题。承接小程序开发。 微信小程序开发交流qq群 173683895 、 526474645 ; 正文: 对象转数组: var jiu res.data.k4.f3var nArr [];for (var i in jiu){nArr.push(jiu[i]);}console.log(jiu);consol…

sql 事务使用

BEGIN TRAN Tran_Money --开始事务DECLARE tran_error int; SET tran_error 0;BEGIN TRY UPDATE tb_Money SET MyMoney MyMoney - 30 WHERE Name 刘备;SET tran_error tran_error ERROR;--测试出错代码,看看刘备的钱减少,关羽的钱是否会增加--SE…

一群算法_树遍历解释:他们就像一群懒惰的学生,试图欺骗他们的考试

一群算法by Sachin Malhotra由Sachin Malhotra 树遍历解释:他们就像一群懒惰的学生,试图欺骗他们的考试 (Tree Traversals explained: They’re like a class of lazy students trying to cheat on their exam) Imagine that you are enrolled in a mat…

微信小程序转发 分享 打电话功能,完整代码附效果图

微信小程序开发交流qq群 581478349 承接微信小程序开发。扫码加微信。 正文&#xff1a; 按钮绑定在页面内发起转发事件onShareApp:(注意这里是button 并且给他设置了open-type"share" 属性) <button classbottom_1 bottom_1_zf open-type"share" bi…

《DSP using MATLAB》示例 Example 6.25

代码&#xff1a; % x [-0.9, 0.81]; [y, L, B] QCoeff(x, 3) % Unquantized parameters r 0.9; theta pi/3; a1 -2*r*cos(theta); a2 r*r; p1 r*exp(j*theta); p2 p1;% Quantized parameters: N 3; [ahat, L, B] QCoeff([a1, a2], 3); rhat sqrt(ahat(2)); thetah…

sqlserver查询自定义的函数

1)sp_helptext同样适应用自定义函数 2)sys.sql_modules表也可以查 查看函数的源代码: exec sp_helptext 函数名转载于:https://www.cnblogs.com/toSeeMyDream/p/4195030.html

辍学的名人_我辍学去追求成为网络开发人员和设计师的梦想

辍学的名人by Carlos Sz由Carlos Sz 我辍学去追求成为网络开发人员和设计师的梦想 (I dropped out of college to pursue my dreams of being a web developer and designer) When I was 14, I discovered HTML. Thanks to my computer science teacher at school. And from t…

Java中的static关键字的用法

1.静态方法 static&#xff1a;通常在一个类中定义一个方法为static&#xff0c;那就是说&#xff0c;无需本类的对象即可调用此方法 声明为static的方法有以下几条限制&#xff1a; &#xff08;1&#xff09;它们仅能调用其他的static方法。 &#xff08;2&#xff09;它们只…

[微信小程序]上传单张和多张图片

微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 上传单张图片并展示, <button bindtap"upimg" classjia_img >上传</button> <image src"{{tempFilePaths[0]}}"></image> data{ tempFilePaths:[]; },u…

“猪”飞起来了吗

&#xff08;让我们用代码改变世界&#xff0c;也让代码改变自己的生活&#xff09; 台风来了&#xff0c;猪都能飞起来。 这是投资者对A股近期走势最生动的形容。当成交量不断的刷新纪录&#xff0c;直冲1.2万亿天量成交时&#xff0c;股指的高度也在不断的被刷新&#xff0c;…

微信公众号开发本地环境开发_如何在5分钟内使HTTPS在本地开发环境上工作

微信公众号开发本地环境开发Almost any website you visit today is protected by HTTPS. If yours isn’t yet, it should be. Securing your server with HTTPS also means that you can’t send requests to this server from one that isn’t protected by HTTPS. This pos…

pcntl_fork 导致 MySQL server has gone away 解决方案

pcntl_fork 前连数据库&#xff0c;就会报 MySQL server has gone away 错误。原因是子进程会继承主进程的数据库连接&#xff0c;当mysql返回数据时&#xff0c;这些子进程都可以通过这个连接读到数据&#xff0c;造成数据错乱。 该操作数据库的地方还是要操作数据库&#xff…

[微信小程序]滚动选择器

微信小程序开发交流qq群 581478349 承接微信小程序开发。扫码加微信。 正文&#xff1a; <view class"section"><view class"section__title">普通选择器</view><picker bindchange"bindPickerChange" value"{{ind…

北航MOOC客户端

我们的团队作业终于完成了&#xff0c;欢迎下载使用我们的北航MOOC手机客户端软件&#xff08;Android端&#xff09;——北航学堂&#xff0c;学习北航的公开课程。 安装包下载地址&#xff1a; http://pan.baidu.com/s/1jGvH7fS 团队发布博客 http://www.cnblogs.com/sevens/…

大学毕业没有实习经历_我是如何在大学毕业后没有实习的情况下获得第一份开发人员工作的...

大学毕业没有实习经历by Tim Park蒂姆帕克(Tim Park) 我是如何在大学毕业后没有实习的情况下获得第一份开发人员工作的 (How I got my first developer job with no internships straight out of college) 5个关键要素&#xff0c;将在求职中发挥重要作用 (5 key elements tha…

java的线程中断

在java中中断线程可以使用interrupt&#xff08;&#xff09;函数。此函数虽然不能终止线程的运行&#xff0c;但是可以改变线程的状态为true 即&#xff1a;isInterrupted()的值返回为true 注意&#xff1a;当函数调用了已经被阻塞的线程后&#xff0c;被阻塞的线程将会接收到…

验证表单不为空

有问题可以扫码加我微信&#xff0c;有偿解决问题。承接小程序开发。 微信小程序开发交流qq群 173683895 、 526474645 &#xff1b; 正文&#xff1a; 目的 : 验证表单是否为空,如果其中一个input的值为空就alert提示它的 name的值不能为空 , <!DOCTYPE html> &…

java中文乱码解决之道(二)—–字符编码详解:基础知识 + ASCII + GB**

原文出处&#xff1a;http://cmsblogs.com/?p1412 在上篇博文&#xff08;java中文乱码解决之道&#xff08;一&#xff09;—–认识字符集&#xff09;中&#xff0c;LZ简单介绍了主流的字符编码&#xff0c;对各种编码都是点到为止&#xff0c;以下LZ将详细阐述字符集、字符…

swift视图容器_如何使用IBDesignable在Swift中创建漂亮的,可重复使用的渐变视图...

swift视图容器by Lee Dowthwaite通过李道思韦特 如何使用IBDesignable在Swift中创建漂亮的&#xff0c;可重复使用的渐变视图 (How to create a beautiful, reusable gradient view in Swift with IBDesignable) This tutorial will demonstrate how to create a versatile, I…

android 以不规则图片为边框切割另外图片

转自&#xff1a;http://blog.sina.com.cn/s/blog_474928c90101dkvf.html 最近工作上遇到了一个将一个图片按照相框进行裁剪的问题&#xff0c;花了一个下午研究了下&#xff0c;在此整理一下&#xff0c;以便后用。 &#xff08;相片&#xff09; …

L3-010. 是否完全二叉搜索树

L3-010. 是否完全二叉搜索树 时间限制400 ms内存限制65536 kB代码长度限制8000 B判题程序Standard作者陈越将一系列给定数字顺序插入一个初始为空的二叉搜索树&#xff08;定义为左子树键值大&#xff0c;右子树键值小&#xff09;&#xff0c;你需要判断最后的树是否一棵完全二…

[微信小程序]计算自己手机到指定位置的距离

微信小程序开发交流qq群 581478349 承接微信小程序开发。扫码加微信。 正文&#xff1a; 目的: 根据目的地的坐标计算自己手机的位置离目的地的距离的 核心思路: 后续操作必须等所有异步请求都返回了才能继续 使用Promise() const qqmap require("../../utils/qqma…

ai css 线条粗细_如何训练AI将您的设计模型转换为HTML和CSS

ai css 线条粗细by Emil Wallner埃米尔沃尔纳(Emil Wallner) 如何训练AI将您的设计模型转换为HTML和CSS (How you can train an AI to convert your design mockups into HTML and CSS) Within three years, deep learning will change front-end development. It will increa…

Android Layer List 使用实现实例

Layer List是Anroid中的一种图形的方式&#xff0c;它是通过叠加若干张图片的方式来形成最终的图片&#xff0c;最终的图片在代码中表现为一个LayerDrawable对象。 效果图&#xff1a;第一张是默认显示&#xff0c;第二张为按改变按钮后的图 下面通过一个实例来说明&#xff1a…

Promise - js异步控制神器

微信小程序开发交流qq群 581478349 承接微信小程序开发。扫码加微信。 正文&#xff1a; 首先给来一个简单的demo看看Promise是怎么使用的&#xff1a; <!DOCTYPE html> <html><head><meta charset"utf-8"><script type"text/ja…

lab_2 Selenium

1、安装SeleniumIDE插件 添加组件-搜索Selenium IDE 安装后重启浏览器可以看到工具中存在此IDE 2、学会使用SeleniumIDE录制脚本和导出脚本 工具--Selenium IDE&#xff0c;得到界面如图 以百度搜索天津大学为例&#xff0c;如下图 红色的是录制按钮&#xff0c;base url是当前…

android进度指示器_等待的痛苦—浏览进度指示器地狱的7个级别

android进度指示器by Mike Zetlow由Mike Zetlow 等待的痛苦—浏览进度指示器地狱的7个级别 (The Pain of Waiting — Navigating the 7 Levels of Progress Indicator Hell) How much hell are you willing to put your users through?您愿意让用户承受多少痛苦&#xff1f; …

Oracle基础 动态SQL语句

一、静态SQL和动态SQL的概念。 1、静态SQL 静态SQL是我们常用的使用SQL语句的方式&#xff0c;就是编写PL/SQL时&#xff0c;SQL语句已经编写好了。因为静态SQL是在编写程序时就确定了&#xff0c;我们只能使用SQL中的DML和事务控制语句&#xff0c;但是DDL语句&#xff0c;以及…

dataTables常用参数

一、新版本和老版本的区别 新版本的改进&#xff1a;https://datatables.net/new/1.10 新老版本参数变化列表&#xff1a;http://datatables.club/upgrade/1.10-convert.html 老版本参数列表&#xff1a; http://legacy.datatables.net/usage/features http://legacy.datatable…