Home  >  Article  >  Web Front-end  >  Detailed introduction to RxJS implementation of Redux Form (code example)

Detailed introduction to RxJS implementation of Redux Form (code example)

不言
不言forward
2018-12-31 09:55:154588browse

This article brings you a detailed introduction (code example) about the implementation of Redux Form with RxJS. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. helped.

Before reading this article, you need to master the knowledge:

  • React

  • ##RxJS (at least you need to know what Subject is)

Background

Form can be said to be one of the biggest problems in web development. Compared with ordinary components, form has the following characteristics:

  1. More user interactions. This means that a large number of custom components may be needed, such as DataPicker, Upload, AutoComplete, etc.

  2. Frequent status changes. Every time the user enters a value, it may change the application state, requiring the form elements to be updated or an error message to be displayed.

  3. #Form verification is to verify the validity of user input data. There are many forms of form validation, such as validating while typing, validating after losing focus, or validating before submitting the form, etc.

  4. Asynchronous network communication. When user input and asynchronous network communication exist at the same time, there are more things to consider. For example, AutoComplete needs to asynchronously obtain the corresponding data based on the user's input. If the user initiates a request every time he inputs, it will cause a great waste of resources. Because each input is obtained
    asynchronously, the data obtained by two consecutive user inputs may also have a "last come, first served" problem.

It is precisely because of the above characteristics that the development of form becomes difficult. In the next chapters, we will combine RxJS and Form to help us better solve these problems.

HTML Form

Before implementing our own Form component, let us first refer to the native HTML Form.

Save form status

For a Form component, it is necessary to save the information of all form elements (such as value, validity, etc.), and HTML Form is no exception.

So, where does HTML Form save the form state? How can I get form element information?

There are mainly the following methods:

  1. document.forms will return all

    form nodes.
  2. HTMLFormElement.elements Returns all form elements.

  3. event.target.elements can also get all form elements.

  4. document.forms[0].elements[0].value; // 获取第一个 form 中第一个表单元素的值
    
    const form = document.querySelector("form");
    form.elements[0].value; 
    
    form.addEventListener('submit', function(event) {
      console.log(event.target.elements[0].value);
    });
Validation

The types of form validation are generally divided into two types:

  1. Built-in form validation. By default, it will be triggered automatically when the form is submitted. You can turn off the browser's automatic validation by setting the

    novalidate attribute.

  2. JavaScript validation.

  3. 
    
           
Problems

  • Customization is difficult. For example, Inline Validation is not supported, the form can only be verified when submitting, and the style of the error message cannot be customized.

  • It is difficult to deal with complex scenes. Such as nesting of form elements, etc.

  • #The behavior of the Input component is inconsistent, making it difficult to get the value of the form element. For example, checkbox and multiple select cannot directly obtain the value when obtaining the value, and additional conversion is required.

var $form = document.querySelector('form');

function getFormValues(form) {
  var values = {};
  var elements = form.elements; // elemtns is an array-like object

  for (var i = 0; i React Rx Form<h2></h2>Interested students can first take a look at the source code https://github.com/reeli/reac...<p></p>React and RxJS<h3></h3>RxJS is a very powerful data management tool, but it does not have the function of user interface rendering, while React is particularly good at handling interfaces. So why not combine their strengths? Solving our Form puzzle using React and RxJS. Now that we know their respective strengths, the division of labor is relatively clear: <p></p><p>RxJS is responsible for managing the state, and React is responsible for rendering the interface. <strong></strong></p>Design ideas<h3></h3>Different from Redux Form, we will not store the state of the form in the store, but directly save it in <p></p>
in the component. Then use RxJS to notify each of the data, and then the component will decide whether it needs to update the UI based on the data. If it needs to be updated, Call setState, otherwise do nothing. For example, suppose there are three Fields in a Form (as shown below). When only the value of FieldA changes, in order to prevent
and

its subcomponents from also re- Render, Redux Form needs to be restricted internally through
shouldComponentUpdate().

// 伪代码
              
And RxJS can control the granularity of component updates to the minimum. In other words, it allows

re-render that really needs to be re-rendered. Re-rendered components are not re-rendered.

The core is Subject

From the above design ideas, we can summarize the following two issues:

  1. Form and Field have a one-to-many relationship. The status of the form needs to be notified to multiple Fields.

  2. Field needs to modify the state of the component based on data.

第一个问题,需要的是一个 Observable 的功能,而且是能够支持多播的 Observable。第二个问题需要的是一个 Observer 的功能。在 RxJS 中,既是 Observable 又是 Observer,而且还能实现多播的,不就是 Subject 么!因此,在实现 Form 时,会大量用到 Subject。

formState 数据结构

Form 组件中也需要一个 State,用来保存所有 Field 的状态,这个 State 就是 formState。

那么 formState 的结构应该如何定义呢?

在最早的版本中,formState  的结构是长下面这个样子的:

interface IFormState {
  [fieldName: string]: {
    dirty?: boolean;
    touched?: boolean;
    visited?: boolean;
    error?: TError;
    value: string;
  };
}

formState 是一个对象,它以 fieldName  为 key,以一个 保存了 Field 状态的对象作为它的 value。

看起来没毛病对吧?

但是。。。。。

最后 formState 的结构却变成了下面这样:

interface IFormState {
  fields: {
    [fieldName: string]: {
      dirty?: boolean;
      touched?: boolean;
      visited?: boolean;
      error?: string | undefined;
    };
  };
  values: {
    [fieldName: string]: any;
  };
}

Note: fields 中不包含 filed value,只有 field 的一些状态信息。values 中只有 field values。

为什么呢???

其实在实现最基本的 Form 和 Field 组件时,以上两种数据结构都可行。

那问题到底出在哪儿?

这里先买个关子,目前你只需要知道 formState 的数据结构长什么样就可以了。

数据流

Detailed introduction to RxJS implementation of Redux Form (code example)

为了更好的理解数据流,让我们来看一个简单的例子。我们有一个 Form 组件,它的内部包含了一个 Field 组件,在 Field 组件内部又包含了一个 Text Input。数据流可能是像下面这样的:

  1. 用户在输入框中输入一个字符。

  2. Input 的 onChange  事件会被 Trigger。

  3. Field 的 onChange Action 会被 Dispatch。

  4. 根据 Field 的 onChange Action 对 formState 进行修改。

  5. Form State 更新之后会通知 Field 的观察者。

  6. Field 的观察者将当前 Field 的 State pick 出来,如果发现有更新则 setState ,如果没有更新则什么都不做。

  7. setState 会使 Field rerender ,新的 Field Value 就可以通知给 Input 了。

核心组件

首先,我们需要创建两个基本组件,一个 Field 组件,一个 Form 组件。

Field 组件

Field 组件是连接 Form 组件和表单元素的中间层。它的作用是让 Input 组件的职责更单一。有了它之后,Input 只需要做显示就可以了,不需要再关心其他复杂逻辑(validate/normalize等)。况且,对于 Input 组件来说,不仅可以用在 Form 组件中,也可以用在 Form 组件之外的地方(有些地方可能并不需要 validate 等逻辑),所以 Field 这一层的抽象还是非常重要的。

  • 拦截和转换。 format/parse/normalize。

  • 表单校验。 参考 HTML Form 的表单校验,我们可以把 validation 放在 Field 组件上,通过组合验证规则来适应不同的需求。

  • 触发 field 状态的 改变(如 touched,visited)

  • 给子组件提供所需信息。 向下提供 Field 的状态 (error, touched, visited...),以及用于表单元素绑定事件的回调函数 (onChange,onBlur...)。

利用 RxJS 的特性来控制 Field 组件的更新,减少不必要的 rerender。

与 Form 进行通信。 当 Field 状态发生变化时,需要通知 Form。在 Form 中改变了某个 Field 的状态,也需要通知给 Field。

Form 组件

  • 管理表单状态。 Form 组件将表单状态提供给 Field,当 Field 发生变化时通知 Form。

  • 提供 formValues。

  • 在表单校验失败的时候,阻止表单的提交。

    通知 Field 每一次 Form State 的变化。 在 Form 中会创建一个 formSubject$,每一次 Form State 的变化都会向 formSubject$ 上发送一个数据,每一个 Field 都会注册成为 formSubject$ 的观察者。也就是说 Field 知道 Form State 的每一次变化,因此可以决定在适当的时候进行更新。
    当 FormAction 发生变化时,通知给 Field。 比如 startSubmit 的时候。


组件之间的通信

  1. Form 和 Field 通信。

    Context 主要用于跨级组件通信。在实际开发中,Form 和 Field 之间可能会跨级,因此我们需要用 Context 来保证 Form 和 Field 的通信。Form 通过 context 将其 instance 方法和 formState 提供给 Field。

  2. Field 和 Form 通信。

    Form 组件会向 Field 组件提供一个 d__ispatch__ 方法,用于 Field 和 Form 进行通信。所有 Field 的状态和值都由 Form 统一管理。如果期望更新某个 Field 的状态或值,必须 dispatch 相应的 action。

  3. 表单元素和 Field 通信

    表单元素和 Field 通信主要是通过回调函数。Field 会向表单元素提供 onChange,onBlur 等回调函数。

接口的设计

对于接口的设计来说,简单清晰是很重要的。所以 Field 只保留了必要的属性,没有将表单元素需要的其他属性通过 Field 透传下去,而是交给表单元素自己去定义。

通过 Child Render,将对应的状态和方法提供给子组件,结构和层级更加清晰了。

Field:

type TValidator = (value: string | boolean) => string | undefined;

interface IFieldProps {
  children: (props: IFieldInnerProps)=> React.ReactNode;
  name: string;
  defaultValue?: any;
  validate?: TValidator | TValidator[];
}

Form:

interface IRxFormProps {
  children: (props: IRxFormInnerProps) => React.ReactNode;
  initialValues?: {
      [fieldName: string]: any;
  }
}

到这里,一个最最基本的 Form 就完成了。接下来我们会在它的基础上进行一些扩展,以满足更多复杂的业务场景。

Enhance

FieldArray

FieldArray 主要用于渲染多组 Fields。

回到我们之前的那个问题,为什么要把 formState 的结构分为 fileds 和 values?

其实问题就出在 FieldArray,

  • 初始长度由 initLength 或者 formValues 决定。

  • formState 整体更新。

FormValues

通过 RxJS,我们将 Field 更新的粒度控制到了最小,也就是说如果一个 Field 的 Value 发生变化,不会导致 Form 组件和其他 Feild 组件 rerender。

既然 Field 只能感知自己的 value 变化,那么问题就来了,如何实现 Field 之间的联动?

于是 FormValues 组件就应运而生了。

每当 formValues 发生变化,FormValues 组件会就把新的 formValues 通知给子组件。也就是说如果你使用了 FormValues  组件,那么每一次 formValues 的变化都会导致 FormValues 组件以及它的子组件 rerender,因此不建议大范围使用,否则可能带来性能问题。

总之,在使用 FormValues 的时候,最好把它放到一个影响范围最小的地方。也就是说,当 formValues 发生变化时,让尽可能少的组件 rerender。

在下面的代码中,FieldB 的显示与否需要根据 FieldA 的 value 来判断,那么你只需要将 FormValues 作用于 FIeldA 和 FieldB 就可以了。

<formvalues>
    {({ formValues, updateFormValues }) => (
        
            <fielda></fielda>
            {!!formValues.A && <fieldb></fieldb>}
        >
    )}
</formvalues>

FormSection

FormSection 主要是用于将一组 Fields group 起来,以便在复用在多个 form 中复用。主要是通过给 name添加前缀来实现的。

那么怎样给 Field 和 FieldArray 的 name 添加前缀呢?

我首先想到的是通过 React.Children 拿到子组件的 name,再和 FormSection 的 name 拼接起来。

但是,FormSection 和 Field 有可能不是父子关系!因为 Field 组件还可以被抽成一个独立的组件。因此,存在跨级组件通信的问题。

没错!跨级组件通信我们还是会用到 context。不过这里我们需要先从 FormConsumer 中拿到对应的 context value,再通过 Provider 将 prefix 提供给 Consumer。这时 Field/FieldArray 通过 Consumer 拿到的就是 FormSection 中的 Provider 提供的值,而不再是由 Form 组件的 Provider 所提供。因为 Consumer 会消费离自己最近的那个 Provider 提供的值。

<formconsumer>
  {(formContextValue) => {
    return (
      <formprovider>
        {children}
      </formprovider>
    );
  }}
</formconsumer>

测试

Unit Test

主要用于工具类方法。

Integration Test

主要用于 Field,FieldArray 等组件。因为它们不能脱离 Form 独立存在,所以无法对其使用单元测试。

Note: 在测试中,无法直接修改 instance 上的某一个属性,以为 React 将 props 上面的节点都设置成了 readonly (通过 Object.defineProperty 方法)。 但是可以通过整体设置 props 绕过。

instance.props = {
  ...instance.props,
  subscribeFormAction: mockSubscribeFormAction,
  dispatch: mockDispatch,
};

Auto Fill Form Util

如果项目中的表单过多,那么对于 QA 测试来说无疑是一个负担。这个时候我们希望能够有一个自动填表单的工具,来帮助我们提高测试的效率。

在写这个工具的时候,我们需要模拟 Input 事件。

input.value = 'v';
const event = new Event('input', {bubbles: true});
input.dispatchEvent(event);

我们的期望是,通过上面的代码去模拟 DOM 的 input 事件,然后触发 React 的 onChange 事件。但是 React 的 onChange 事件却没有被触发。因此无法给 input 元素设置 value。

因为 ReactDOM 在模拟 onChange 事件的时候有一个逻辑:只有当 input 的 value 改变,ReactDOM 才会产生 onChange 事件。

React 16+ 会覆写 input value setter,具体可以参考 ReactDOM 的 inputValueTracking。因此我们只需要拿到原始的 value setter,call 调用就行了。

const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
nativeInputValueSetter.call(input, "v");

const event = new Event("input", { bubbles: true});
input.dispatchEvent(event);

Debug

打印 Log

在 Dev 环境中,可以通过 Log 来进行 Debug。目前在 Dev 环境下会自动打印 Log,其他环境则不会打印 Log。
Log 的信息主要包括: prevState, action, nextState。

Note:  由于 prevState, action, nextState 都是 Object,所以别忘了在打印的时候调用 cloneDeep,否则无法保证最后打印出来的值的正确性,也就是说最后得到的结果可能不是打印的那一时刻的值。


The above is the detailed content of Detailed introduction to RxJS implementation of Redux Form (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete