react hooks使用

by Austin Malerba

奥斯汀·马勒巴(Austin Malerba)

我如何使用React Hooks在约100行代码中构建异步表单验证库 (How I built an async form validation library in ~100 lines of code with React Hooks)

Form validation can be a tricky thing. There are a surprising number of edge cases as you get into the guts of a form implementation. Thankfully, there are many form validation libraries out there which provide the necessary flags and handlers to implement a robust form, but I challenged myself to build one in under 100 lines of code using the React Hooks API (currently in alpha). As React Hooks are still an experimental proposal, this is a proof of concept for the application of React Hooks to implement form validation.

表单验证可能是一件棘手的事情。 当您进入表单实现的勇气时,会有很多令人惊讶的情况。 值得庆幸的是,那里有许多表单验证库,它们提供了实现可靠表单所需的标志和处理程序,但我挑战自己使用React Hooks API (当前为Alpha)在100行以下代码中构建一个。 由于React Hooks仍是实验性建议,因此这是应用React Hooks实施表单验证的概念证明。

Also, fair warning, the library I build is 100 lines of code, but this tutorial has ~200 lines of code because I need to show how the library is used.

同样,警告一下,我建立的是100行代码,但是本教程有约200行代码,因为我需要说明如何使用该库。

Many form tutorials I’ve seen fail to address three big topics: async validation, field validations that should be triggered when other fields change, and optimization of validation frequency. I am bothered by tutorials that focus on a single use case and hold all other variables constant because that’s not how the real world works, so I will try to hit a variety of use cases.

我见过的许多表单教程都无法解决三个主要主题: 异步验证 ,当其他 字段发生更改时应触发的字段验证以及验证频率的优化。 我被那些只关注单个用例并保持所有其他变量不变的教程所困扰,因为这不是现实世界的工作原理,因此我将尝试使用各种用例。

Let’s aim to satisfy the following:

让我们努力满足以下条件:

  • Synchronously validate a field and any dependent fields when the field value changes当字段值更改时,同步验证字段和任何从属字段
  • Asynchronously validate a field and any dependent fields when the field value changes当字段值更改时,异步验证字段和任何从属字段
  • Synchronously validate all fields before submitting提交前同步验证所有字段
  • Asynchronously validate all fields before submitting提交前异步验证所有字段
  • Attempt async submission and if the form fails to submit, display errors from the response尝试异步提交,如果表单提交失败,则显示响应中的错误
  • Expose validation methods to the developer so the developer can validate onBlur or at other times that make sense向开发人员公开验证方法,以便开发人员可以验证onBlur或在其他有意义的时间进行验证
  • Allow multiple validations per field允许每个字段进行多次验证
  • Disable submission if the form has errors如果表单有误,请禁用提交
  • Do not show a field’s errors until it has been changed or until a form submission has been attempted在更改字段或尝试提交表单之前,请勿显示该字段的错误

We will hit these use cases by implementing an account registration form with a username, password, and password confirmation. Below I’ve outlined the kind of interface we’re looking for, we will build a library to satisfy this contract.

我们将通过实施带有用户名,密码和密码确认的帐户注册表格来解决这些用例。 在下面,我概述了我们正在寻找的接口类型,我们将构建一个库来满足此合同。

This is a relatively simple API, but should give us a lot of flexibility. You might have noticed that this interface includes two similarly named functions, validation and validate. We will define a validation as a function that takes in form data and a field name and returns an error message if an issue is found, otherwise it will return a falsey value. On the other hand, a validate function will run all validation functions for a field and will update the field’s error list.

这是一个相对简单的API,但是应该给我们带来很大的灵活性。 您可能已经注意到,该接口包括两个相似命名的函数,验证和验证。 我们将验证定义为接受表单数据和字段名称的函数,如果发现问题,则返回错误消息,否则将返回falsey值。 另一方面,验证功能将为一个字段运行所有验证功能,并将更新该字段的错误列表。

First things first, we need a skeleton to handle value changes and form submission. Our first iteration will not include any validation, it will merely handle form state.

首先,我们需要一个框架来处理价值变更和表单提交。 我们的第一次迭代将不包含任何验证,它将仅处理表单状态。

There’s nothing too crazy happening in this code. The only state we track is the field values. We have each field register itself with the form at the end of its initialization. Our onChange handlers are simple. The most intimidating function in here is getFormData, but even this is pretty trivial behind the unsightly reduce syntax. getFormData iterates over the form fields and gives us a plain object representation of the form values. The last thing I feel I should explain is that we need to call preventDefault on submit to prevent the page from reloading.

这段代码中没有什么太疯狂的事情了。 我们跟踪的唯一状态是字段值。 在初始化结束时,我们会将每个字段本身与表单一起注册。 我们的onChange处理程序很简单。 这里最令人生畏的功能是getFormData,但是即使在难看的reduce语法后面,这也是微不足道的。 getFormData遍历表单字段,并为我们提供表单值的简单对象表示形式。 我要解释的最后一件事是,我们需要在Submit上调用preventDefault,以防止重新加载页面。

This is good and dandy, but let’s add support for validations now. We won’t yet specify which fields should be validated when a field value changes. Instead, we’ll validate all fields whenever a value changes and whenever the form is submitted.

这很好,但现在让我们添加对验证的支持。 当字段值更改时,我们尚未指定应验证哪些字段。 取而代之的是,只要值更改和表单提交,我们都会验证所有字段。

The above code is an improvement and, at first glance, it seems like it could work well, but it’s actually quite sloppy to the end user. It’s missing a lot of necessary flags that help prevent errors from showing at inappropriate times. It immediately validates fields before the user has had a chance to modify them and displays corresponding errors.

上面的代码是一个改进,乍看之下似乎可以很好地工作,但对于最终用户来说却相当草率 。 它缺少许多必要的标志,这些标志有助于防止错误在不适当的时间显示。 在用户有机会修改字段之前,它将立即验证字段并显示相应的错误。

At the very least we need a pristine flag to tell the UI not to show errors if the user hasn’t changed a field. But let’s go further. In addition to a pristine flag, we will want a few more flags.

如果用户未更改字段,至少需要一个原始标志来告诉UI不显示错误。 但是,让我们走的更远。 除了原始标志之外,我们还将需要一些其他标志。

We will want a flag to indicated that the user has attempted to submit the form and we will want flags to indicate when the form is submitting and when each field is validating asynchronously. You may also be wondering why we invoke validateFields inside useEffect as opposed to inside of the onChange handler. We need useEffect because setValue happens asynchronously and neither returns a promise nor offers a callback. Therefore, the only way we can be sure setValue has completed, is by listening to a value change via useEffect.

我们将需要一个标志来指示用户已尝试提交表单,并且我们将需要标志来指示何时提交表单以及何时每个字段进行异步验证。 您可能还想知道为什么我们在useEffect内部而不是onChange处理程序内部调用validateFields。 我们需要useEffect,因为setValue异步发生,既不返回promise,也不提供回调。 因此,我们可以确保setValue已完成的唯一方法是通过useEffect监听值更改。

Let’s implement the flags I mentioned to help clean up the UI and to handle some edge cases.

让我们实现我提到的标志,以帮助清理UI并处理一些边缘情况。

Our final iteration adds a lot. It adds four flags: pristine, validating, submitted, and submitting. It also adds the fieldsToValidateOnChange parameter, which is passed to validateFields to indicate which fields should be validated when a field value changes. We use these flags in the UI to control when spinners and errors are displayed as well as to disable the submit button.

我们的最终迭代增加了很多。 它添加了四个标志:原始,正在验证,已提交和正在提交。 它还添加了fieldsToValidateOnChange参数,该参数传递给validateFields,以指示当字段值更改时应验证哪些字段。 我们在UI中使用这些标志来控制何时显示微调框和错误以及禁用“提交”按钮。

One peculiar thing you may have noticed is the validateCounter. We need to track how many times the validate function has been called because by the time our validate function has reached completion, it’s possible that validate will have been called again. If this is the case, we need to ignore the results of this invocation and only use the results of the most recent invocation to update the error state for a field.

您可能已经注意到的一件事是validateCounter。 我们需要跟踪验证函数被调用了多少次,因为到验证函数完成时,很有可能会再次调用验证。 在这种情况下,我们需要忽略该调用的结果,而仅使用最近一次调用的结果来更新字段的错误状态。

When all is said and done, here is the functional result.

说完一切,这就是功能结果。

React Hooks provide a neat solution to form validation. This is my first experimentation with the proposed API and I have found it powerful, but a little awkward. The interface is peculiar, with a bit too much magic for my liking. However, once I accepted its blemishes, it proved quite capable.

React Hooks为表单验证提供了一个简洁的解决方案。 这是我对所建议的API的首次实验,我发现它功能强大,但有点尴尬。 界面很独特,我喜欢的魔术太多了。 但是,一旦我接受了它的瑕疵,就证明了它的能力。

I did feel it was lacking a few features, namely a callback mechanism to indicate when a useState setter has finished updating the state and also a way to inspect prop deltas in the useEffect hook.

我确实感觉它缺少一些功能,即一种用于指示useState设置程序何时完成状态更新的回调机制,以及一种用于检查useEffect挂钩中的prop增量的方法。

后注 (After Note)

I have intentionally left out some argument validation and error handling in order to keep this tutorial brief and simple to follow. Take, for example, the way I do not check whether the form passed into a field is indeed a form. It would be a lot nicer to check this explicitly and to throw a verbose error. However, as I have written it, the code would bomb out with something like

为了使本教程简短易懂,我特意省略了一些参数验证和错误处理。 以我不检查传递到字段中的表单是否确实是表单的方式为例。 显式地检查并抛出冗长的错误会好得多。 但是,正如我所写的那样,代码会像

Cannot read property ‘addField’ of undefined

This code needs proper argument validation and error handling before it could ever be published as an npm library. That said, I have implemented a more robust version that includes argument validation via superstruct if you would care to check it out.

该代码需要适当的参数验证和错误处理,然后才能作为npm库发布。 就是说,我已经实现了一个更强大的版本 ,如果您愿意检查的话,它包括通过superstruct进行参数验证。

翻译自: https://www.freecodecamp.org/news/how-i-built-an-async-form-validation-library-in-100-lines-of-code-with-react-hooks-81dbff6c4a04/

react hooks使用

react hooks使用_我如何使用React Hooks在约100行代码中构建异步表单验证库相关推荐

  1. angular js创建表单_如何优雅的使用 Angular 表单验证

    随便说说,这一节可以跳过 去年参加 ngChine 2018 杭州开发者大会的时候记得有人问我: Worktile 是什么时候开始使用 Angular 的,我说是今年(2018年) 3 月份开始在新模 ...

  2. react hooks使用_如何开始使用React Hooks:受控表格

    react hooks使用 by Kevin Okeh 由Kevin Okeh 如何开始使用React Hooks:受控表格 (How to Get Started With React Hooks: ...

  3. 群里分享的react的收藏一下!今日周末,改了个表单验证然后无所事事了!

    今日周末,改了个表单验证然后无所事事了,然后把昨天群里分享的react的收藏一下尽管现在还在研究angular和nodeJs毕竟刚刚开始用有点不熟...没准以后会研究一下react毕竟看着下面这张图还 ...

  4. 表单必填标星_怎么用JS做form表单验证,要详细代码,求救!(带星号的是必填项)...

    匿名用户 1级 2014-06-17 回答 举个例子吧: <input type="text" id="telephone" > <input ...

  5. 微信提示在客户端提交验证_微信小程序之表单验证

    1 /**2 * 表单验证3 *4 * @param {Object} rules 验证字段的规则5 * @param {Object} messages 验证字段的提示信息6 *7 */ 8 cla ...

  6. react全局方法_前端面试题 ---react

    高阶组件相关 什么是高阶组件,它有哪些运用? 高阶组件就是一个函数,接收一个组件,经过处理后返回后的新的组件: 高阶组件,不是真正意义上的组件,其实是一种模式: 可以对逻辑代码进行抽离,或者添加某个共 ...

  7. react 谷歌地图_谷歌地图与React

    react 谷歌地图 情况(The Situation) Your working on a React-based application and you want to implement Goo ...

  8. 使用react的好处_聊一聊我对 React Context 的理解以及应用

    前言 Context被翻译为上下文,在编程领域,这是一个经常会接触到的概念,React中也有. 在React的官方文档中,Context被归类为高级部分(Advanced),属于React的高级API ...

  9. react 项目实战(三)表单验证

    我们需要记录每一个字段当前的有效状态,有效时隐藏错误信息,无效时显示错误信息. 而这个有效/无效,可以在表单值改变的时候进行判断. 我们对/src/pages/UserAdd.js进行修改: 首先修改 ...

最新文章

  1. 逃离无声的世界,跟AI一起听叶落的声音
  2. 新发现判断一个点在多边形的最高效率算法 推荐******
  3. 「一本通 6.4 例 4」曹冲养猪(CRT)
  4. cad里面f命令用不了_CAD出现命令无效、失灵等问题?不用慌,两招帮你快速解决...
  5. linux的进程/线程/协程系列3:查看linux内核源码——vim+ctags/find+grep
  6. 关于计应151/152《软件工程》课程实践的安排
  7. Pandas——merge(合并)
  8. slice()和splice()、split(),number()、parseInt()和parseFloat()
  9. SetStretchBltMode() 防止图片失真
  10. abaqus盾构隧道建模实例_abaqus盾构施工模拟
  11. 戴尔台式计算机键盘,dell键盘失灵怎么解决【图文教程】
  12. Type-C PD协议取电SINK受电端9V12V15V20V
  13. pta——特立独行的幸福
  14. 字节跳动构建Data Catalog数据目录系统的实践
  15. 如何写简单实用的产品需求文档PRD
  16. ES索引生命周期管理ILM
  17. 自定义8583模板,打包解包,使用j8583包有改动
  18. linux串口操作及设置
  19. 巴西龟饲养日志-----日常护理
  20. 中兴 Axon 40 Ultra参数评测 中兴 Axon 40 Ultra配置怎么样 中兴 Axon 40 Ultra值得买吗

热门文章

  1. 公司的年度汇报怎么写 年底述职报告写法
  2. 1218 鼠标样式 cursor
  3. 02 掌握实现数据导入导出的方法 1214
  4. 云题库进入其它章节的办法 0925
  5. request对象的常用属性与方法-103.课时103.【Django视图高级】HttpRequest对象讲解(Av61533158,P103)
  6. django-解决-修改过的模型类不能被正常迁移的解决办法
  7. 数据结构与算法-字典的时间复杂度
  8. botstrap-栅格布局与栅格偏移
  9. python-模块的嵌套调用-随堂草稿件
  10. metronic 4.5.7开发环境下, 在Windows 10上安装了10.16.0版本的node js之后,导致node sass无法加载...