This is the 4th day of my participation in the August More Text Challenge

preface

In this article, we will introduce some practical ways to improve your code during the development process.

Specify default values

When reading properties we hope, the attribute value in the null or undefined can specify a default value, avoid references to bugs, we can use the | | operator

For example, if the message returned by the backend data is null, we use our automatically defined text
const { message } = response.data;
const myMessage = message || 'Return data failed'
Copy the code

Note that the default values also apply if message has a value of “” or false or 0. But if it is {}, or [], the default is not taken!

The default argument to the function replaces the short-circuit operator

const useName = (name) = > {
  const myName = name || "Jason";
  // ...
}

const useName = (name = "Jason") = > {
  // ...
}
Copy the code

&& replaces a single if

For example, when interacting with background data, it is necessary to traverse the returned data for operation.

// To avoid data being traversed for arrays
if(Array.isArray(data)) {
    data.forEach(item= >{})}// Use the && operator to loop through data returned by the request interface:
Array.isArray(data) && data.forEach(item= > {})

Copy the code

Ternary operation symbol

The trinary operator simplifies our if else conditions, and we can use it to simplify our code as appropriate

let key = value === 0 ? "buy" : "sell"
Copy the code

Or if there’s a third case we can nest

let key = ""
if(value === 0) {
    str = "buy"
} else if (value === 1) {
    str = "/"
}  else {
    str = "sell"
}

// create a nested table
let str =  value === 0 ? "buy" : value === 1 ? "/" : "sell"
Copy the code

Chain judgment operation symbol? .

Often, when we need to obtain a deep object attribute value, we need to make several judgments. If we do not judge, an error will be reported if there is no one, resulting in the following code cannot run, and it will prompt:

Cannot read property ‘xxx’ of undefined

const $name = app.config.globalProperties.$name // error

const $name =
      (app &&
       app.config &&
       app.config.globalProperties &&
       app.config.globalProperties.$name) ||
      "Jason";

/ / use? The operator
const$name = app? .config? .globalProperties? .$nameCopy the code

Deconstruction assignment

Data deconstruction assignment

When multiple variables are assigned, we can use data to deconstruct the assignment

let name = "Jason";
let age = "18";
let sex = "Male";

// Array destruct assignment
let [name, age, sex] = ["Jason"."18"."Male"];
Copy the code

Object deconstruction value

const userInfo = {
    name: "Jason".age: "18".sex: "Male"};const { name, age, sex } = userInfo;

// By the way, the same name of a key in an ES6 object can be abbreviated
const name = "Jason"
const userInfo = {
    name,
    ...
};
Copy the code

.Extended operator

The extension operator can also be the equivalent of concat() to concatenate two arrays, such as a list of items on mobile that needs to be paginated

Using template characters

ES6 template strings allow us to concatenate strings without much fuss

// For example, get time concatenation
function getYearsMonthDay() {
    function addDateZero(num) {
        return num < 10 ? "0" + num : num;
    }
    const d = new Date(a);const [years, month, day] = [d.getFullYear(), d.getMonth(), d.getDate()];
   
    return return years + "Year" + addDateZero(month + 1) + "Month" + addDateZero(day) + "Day"
}

// Template string
function getYearsMonthDay() {
    // ...
    return `${years}years${addDateZero(month + 1)}month${addDateZero(day)}Day `;
}
Copy the code

Use let, const instead of var

This prevents the inner layer from overwriting the outer variables and reduces the source of bugs. The specification of lets and const also improves the efficiency of code compilation.

var name = "Jason"

// better
const name = "Jason"

// let is used if it is not a constant
let name = "Jason"
Copy the code

Arrow function

Arrow function expressions have a more concise syntax than function expressions.

// Use vue3 computed here
// function
const statusArr = [2.4.5.6.8.9];
const showBtn = computed(() = > {
    return function (status) {
        return statusArr.includes(status);
    };
});

// Use the arrow function
const computedShowBottomBtn = computed(
    () = > (status) = > statusArr.includes(status)
);
Copy the code

Ps: Haha, but if you use arrow function, you need Babel conversion, the larger the volume, the more conversion you need, so? ~

Return reduces indentation

if(! isObjEmpty(data)) {// do something
}

if(isObjEmpty(data)) return
// ...
Copy the code

Simplified judgment

Conditions for extracting

When an if condition requires more than one case, we can extract the condition and make the code clearer.

if ((name === "Jason" || sex === 20) && (name === "Alisa" || sex === 18)) {
    // ...
}

/ / improvement
const condition1 = () = > {
    return name === "Jason" || sex === 20;
};

const condition2 = () = > {
    return name === "Alisa" || sex === 18
}

if (condition1() && condition2()) {
    // ...
}
Copy the code

Includes a simplified

The includes() method is used to determine whether an array contains a specified value, returning true if it does and false otherwise.

Such as determining whether a value meets one of these conditions

/ / usually use | |
if (status === 2 || status === 3 || status === 4 || status === 5) {
    // do something
}

/ / includes a simplified
const passStatus = [2.3.4.5]
if (passStatus.includes(status)) {
    // do something
}

Copy the code

switch

Multi-condition judgment, common switch can be used to judge:

Such as a message that customizes the status code based on the returned request status

switch(error.response.status) {
    case 302: message = 'Interface redirected! ';break;
    case 400: message = 'Incorrect parameters! ';break;
    case 401: message = 'You have not logged in, or the login has timed out, please log in first! ';break;
    case 403: message = 'You have no permission to operate! '; break;
    case 404: message = 'Error requesting address:${error.response.config.url}`; break;
    case 408: message = 'Request timed out! '; break;
    case 409: message = 'Same data already exists in system! '; break;
    case 500: message = 'Server internal error! '; break;
    case 501: message = 'Service not implemented! '; break;
    case 502: message = 'Gateway error! '; break;
    case 503: message = 'Service unavailable! '; break;
    case 504: message = 'Service temporarily inaccessible, please try again later! '; break;
    case 505: message = 'HTTP version not supported! '; break;
    default: message = 'Request exception'; break
}
Copy the code

Abstract configuration

Or it is easier to simplify logical judgments by abstracting configuration key values.

const mapMessage = {
    302: "Interface redirected!".400: "Incorrect parameters!".401: "You are not logged in, or the login has timed out, please log in first!".403: "You have no permission to operate!".404: 'Error requesting address:${error.response.config.url}`.408: "Request timed out!".409: "Same data already exists in system!".500: "Server internal error!.501: "Service not implemented!".502: "Gateway error!".503: "Service unavailable!".504: "Service temporarily inaccessible, please try again later!".505: "HTTP version not supported!"};const message = mapMessage[error.response.status] || "Request exception"
Copy the code

The advantage of this approach is that the judgment condition is the attribute name and the processing logic is the attribute value of the object.

Using the map

const action = new Map([[302."Interface redirected!"],
    [400."Incorrect parameters!"],
    ...
]);

/ / match
const message = action.get(error.response.status);
Copy the code

Form judgment optimization

Some requirements have multiple forms. Generally, our UI frameworks (such as Vant and ant-d) have a warning under the input component, but some columns, such as upload, and swtich have no corresponding prompt, requiring us to pop up to indicate that it is not filled in or selected, etc.

Bad ways to write:

if(! CardPositiveImage) { createMessage('No upload ID front! ');
   return false;
}
if(! name) { createMessage('No name! ');
    return false;
}
if(! checkPhone(phone)) { createMessage('Wrong number! ');
    return false;
}
// ...
Copy the code

A good way to write:

const validateForm = () = > {
    const rules = [
        {
            value: CardPositiveImage,
            text: "Did not upload certificate front!"}, {value: checkPhone(state.patientPhone),
            text: "Wrong number!"}, {value: name,
            text: "No name!",},];// We can also separate the validateFunc from the validateFunc
    const validateFunc = (arr) = > {
        const action = arr.filter(item= >! item.value);if (action.length) {
            createMessage(action[0].text);
            return false
        }
        return true
    }
    return validateFunc(rules);
};

// Form submission
const onSubmitForm = () = > {
    if(! validateForm())return // Perform validation
    
    // ...
}
Copy the code

Function with too many arguments, passed with Object, and destructed

👎
const getUserInfo = (name, sex, height, age) = > {
    // ...
};
getUserInfo("Jason"."Male"."176"."18");

👍
const getUserInfo = ({ name, age, sex, height }) = > {
    // ...
};
getUserInfo({
    name: "Jason".age: "18".sex: "Male".height: "176"});Copy the code

Single responsibility, refine function

A quick example is a function that is responsible for form submission

👎
const handleNext = () = > {
    // Validate the form
	const rules = [
        {
            value: CardPositiveImage,
            text: "Did not upload certificate front!"}, {value: checkPhone(state.patientPhone),
            text: "Wrong number!"}, {value: name,
            text: "No name!",},];const action = rules.filter(item= >! item.value);if (action.length) {
        createMessage(action[0].text);
        return false
    }
    
   // Get the data to be passed to the back end
   const baseData = {
       name: state.name,
       age: state.age
       ...
   }
   const moreData = {
       phone: state.phone
       ...
   }
   
   const complete = curIndex ? Object. Assign (baseData, moreData) : baseData} 👍const validateForm = () = > {
    const rules = [
        {
            value: CardPositiveImage,
            text: "Did not upload certificate front!",},... ] ;// We can also separate the validateFunc from the validateFunc
    const validateFunc = (arr) = > {
        const action = arr.filter(item= >! item.value);if (action.length) {
            createMessage(action[0].text);
            return false
        }
        return true
    }
    return validateFunc(rules);
};

const postData = () = > {
    const baseData = {
        name: state.name,
        age: state.age
        ...
    }
    const moreData = {
        phone: state.phone
        ...
    }

    return curIndex ? Object.assign(baseData, moreData) : baseData
}

const handleNext = () = > { 
    // Validate the form
    if(! validateForm())return 
    / / data
    const data = postData()
    
    / /.. Submit a request
}
Copy the code

The last

How to use Vue and React framework to write components gracefully is also a question of knowledge, behind explore research ~