preface

The content of this article is based on their own daily development experience, mainly some actual combat tips and trample pit experience, I hope to be of help to you, the deficiencies also ask you to give more advice. Continuously updated ~

annotation

Get into the habit of writing notes for your own good. Put yourself in the shoes of your colleagues and be concise.

  • Single-line comments
Function toStr(v) {return v.tostring (); function toStr(v) {return v.tostring (); }}Copy the code
  • Multiline comment
/** * In multi-line comments, any character * contained between the /** and the */ symbol is treated as comment text */Copy the code
  • Annotation prefix
// FIXME: List update has bug, need to be fixedCopy the code

Import module order

  • Third party’s on top
  • Then there are the other modules of the current project
  • Finally, CSS styles
import * as React from 'react;
import {Button, Input} from 'antd';
import Header from './Header';
import {Status} from './const';
import * as styles from './index.less';
Copy the code

Code style.

Here are the prevailing coding styles, subject to team specifications.

  • Use single quotes, or es6 backquotes
  • Every expression other than a code block must end with a semicolon
  • Variables and functions are named with small humps
  • Constants are named in uppercase letters and words are separated by underscores, such as STATUS_MAP
  • Event functions within the component start with handle, for example, handleConfirm
  • When passing the function through porps, use the form onXxx as the attribute name of the callback function
const App = () => {
    const handleCancel = () => {
        ...
    }
    
    return (
        <div>
            Hello !
            <Child onClose={handleCancel}/>
        </div>
    )
}
Copy the code
  • Don’t omit the curly braces too much
// not good
if(condition) doSomething();

// good
if (condition) {
    doSomething();
}
Copy the code

semantic

State and function names should be semantically named so that people immediately know what value the state represents and what event the function handles after reading an English word, and avoid code with unknown meanings.

// not good 
const [value, setValue] = useState();

// good
const [checkedValue,setCheckedValue] = useState();
Copy the code
// not good
const handleClick = () => {}

// good
const handleConfirm = () => {}
Copy the code
// bad if (type! == 0) { // TODO } // good const STATUS = { FAILED: 0, SUCCESS: 1,} if (type === status. SUCCESS) {// TODO} // best (TS enumeration) enum STATUS {FAILED = 0, SUCCESS = 1,}Copy the code

Render defaults

Adding non-null judgments, using defaults for prevention, improves code robustness. For example, some values returned from the back end may not exist, so giving a default value can avoid many defects.

const res = request(); If (res && res.success) {message.success(' delete successfully '); } else {/ / if the specific cause of the failure of the backend is not exposed, suggests that 'delete failed message. Error (res) message | |' delete failure); }Copy the code

In another case, the back end might return null if it was supposed to return an array, but no data was retrieved from the database. If there is a list. Length condition in the code, the error will be reported. The simplest solution is to add non-null judgments and default values.

const [listData, setListData] = useState([]); const { data: { list } } = request(); / / if the list is null, it will take [], the listData below. The length is not an error setListData (list | | []) if (listData. Length > 0) {... }Copy the code

Data format conversion

It is important to pay attention to whether the data type returned by the back end meets our expectations during development, which can sometimes cause problems.

For example, we get an ID of type string, but we need to pass in type number when calling other interface parameters, which can easily be ignored. The following two methods of converting strings to numbers are equivalent.

const a = '2022'; console.log(+a); // 2022(number) simplest console.log(number (a)); // 2022(number)Copy the code

Another case to note is that the ‘Boolean’ returned from the back end is actually a string: ‘false’, ‘true’. Always true if we use it directly. Once because of this problem caused a bug almost gave me the whole breakdown ~

Conversion to Booleans is recommended using dual logic non!!

console.log(!! 0); // false console.log(!! 1); // true console.log(!!" "); // false console.log(!! null); // false console.log(!! undefined); // false console.log(!! []); // true console.log(!! {}); // trueCopy the code

Determine whether the condition is true or false

The following is false and the others are true.

  • false
  • null
  • undefined
  • 0
  • “(empty string)
  • NaN

Deconstruction assignment

Write code as succinct as possible, so that it is easier to read and maintain later. Using deconstructed assignment caching frequently used attributes or values for later use is more convenient.

// bad
props.data.id;
props.data.username;
state.detail.status;

// good
const { id, username } = props.data;
const { status } = state.detail;
Copy the code

Input input box empty space

// bad
const handleInputChange = (e) => {
    setInputValue(e.target.value);
}

// good
const handleInputChange = (e) => {
    setInputValue(e.target.value.trim());
}
Copy the code

try catch

When you send an Ajax request, you use a try catch to catch errors, or you can do something based on the returned state. For example, to enter the list page, a loading state is required first, and then data is requested. Whether the request succeeds or fails, loading must be removed.

const getList = async () => { try { setLoading(true); const res = await request(); } catch (err) { // TODO } finally { setLoading(false); }}Copy the code

Prevents event default behavior

React cannot prevent the default behavior by returning false, it must explicitly call event.preventDefault().

To prevent a bubble

event.stopPropagation()

Reduce useEffect dependencies

The more useEffect dependencies there are, the more complexity there is and the more bugs there are.

// bad function Component({ id, name }) { useEffect(() => { setId(id); setName(name); }, [id, name... more]); } // good function Component({ id, name }) { useEffect(() => { setId(id); }, [id]); useEffect(() => { setName(name); }, [name]); }Copy the code

key

Keys must only be unique between siblings, not globally unique. Avoid using index and date as key values. If you really can’t get a unique value, you can use the Nanoid library to generate uuid (universal unique identifier).

NPM I nanoid import {nanoid} from 'nanoid' {uUID key={nanoid()}Copy the code

Component instances are updated and reused based on their key. If the key is a subscript, the index changes when the order is changed, i.e. the current key changes. This can cause the states of uncontrolled components (such as input fields) to tamper with each other and change in unexpected ways.

Keys should be unique, stable, and predictable. Unstable keys (such as new Date(), math.random ()) cause many component instances and DOM nodes to be recreated unnecessarily, which can lead to performance degradation and loss of state in child components.

Your thumbs-up is a great encouragement to me! Thanks for reading ~