preface

Antd and ANTD proComponents are commonly used in the UI framework of our project. For the Form Form, such a function is exposed as onValuesChange, and the code is as follows:

onValuesChange={(changedValues: any, values: any) = > {
    console.log('% c changedValues ⧭'.'color: #ffa280', changedValues);
    console.log('% values c = ⧭'.'color: #997326', values);
}}
Copy the code
The problem

For example, a Form fields is the following data structure:

const initialForm = {
    name: 'Bob'.age: 11.sex: 'male',}Copy the code

If the name of the form is changed to ‘Tom’, the onValuesChange function will be triggered and changedValues will print the following object:

const changedValues = {
    name: 'Tom',}Copy the code

Some requirements need to know the old value and the new value, and some requirements only need to know which values have changed, so how to determine whether there is a property change requires a method to determine, ANTD does some processing in this layer, changedValues will only return a filtered object containing the changed property.

Judgment method

There have been attempts to do this before

if(changedValues? .name) {// ...
}
Copy the code

However, this does not solve the situation where the value is changed to undefined, so you still need to use the presence of the attribute to determine whether it is correct.

There are two ways, as follows:

// 1. Object.prototype.hasOwnProperty()
if (changedValues.hasOwnProperty('name')) {
    // ...
}

// 2. key in object
if ('name' in changedValues) {
    // ...
}

// 3. Reflect.has()
if (Reflect.has(changedValues, 'name')) {
    // ...
}
Copy the code