preface

Team each developer in different levels, technical focus is different, if you don’t have a code specification reference and constraints, the code in the project will be different style, it is difficult to maintain, in order to ensure the code quality and the style is unified, we proposed a team React code specification, so that the entire team of developers can consult the encoded code specification, In this way, the team’s code style is unified and easy to maintain. If your team doesn’t already have a React code specification, this is probably what you need; If your team already has the React code specification, this specification may be the icing on the cake.

Note: code specifications for JS, SCSS, Vue can be found in another article written by the authorFront-end Team Code Review CheckList.

Hard to sort out for a long time, but also hope to manually praise encouragement ~

Making address:Click here to, if you like or have some inspiration, please help to give a star ~, to the author is also a kind of encouragement.

1. Basic rules

  • Declare one component in a file: Although it is possible to declare multiple React components in a file, it is best not to do so; It is recommended that a file declare a React component and export only one component.
  • Use JSX expressions: Don’t write React. CreateElement;
  • Usage scenarios of function and class components: If the defined component does not need props and state, it is recommended to define the component as a function component; otherwise, it is recommended to define the component as a class component.

Component declaration

(1) It is recommended that the name of the component be the same as the name of the file that defines the component;

Recommendation:

import Footer from './Footer';
Copy the code

Is not recommended:

import Footer from './Footer/index';
Copy the code

(2) Do not use the displayName attribute to define the component name. Instead, declare the component name directly after the class or function keyword.

Recommendation:

export default class MyComponent extends React.Component {}Copy the code

Is not recommended:

export default React.Component({
  displayName: 'MyComponent'});Copy the code

React naming

  • Component name: Large hump is recommended;
  • Attribute names: React DOM uses the small hump command to define attribute names, rather than the HTML naming convention for attribute names;
  • Style style attribute: JavaScript object with small camel name attribute;

Recommendation:

// Component name
MyComponent
// Attribute name
onClick
// Style attributes
backgroundColor
Copy the code

4. Pay attention to JSX writing

4.1, tags,

(1) Always use a self-closing tag when the tag has no child elements.

Recommendation:

// Good
<Component />
Copy the code

Is not recommended:

<Component></Component>
Copy the code

(2) If the tag has multiple line attributes, close the tag on another line.

Recommendation:

<Component
  bar="bar"
  baz="baz" 
/>
Copy the code

Is not recommended:

<Component
  bar="bar"
  baz="baz" />
Copy the code

(3) Leave a space before the autistic label.

Recommendation:

<Foo />
Copy the code

Is not recommended:

<Foo/>

<Foo                 />

<Foo
 />
Copy the code

(4) Enclose the JSX tag with parentheses when components cross rows.

Recommendation:

  render() {
    return (
      <MyComponent className="long body" foo="bar">
        <MyChild />
      </MyComponent>
    );
  }
Copy the code

Is not recommended:

  render() {
    return <MyComponent className="long body" foo="bar">
             <MyChild />
           </MyComponent>;
  }
Copy the code

4.2, alignment

JSX syntax uses the following alignment:

/ / recommend
<Foo
  superLongParam="bar"
  anotherSuperLongParam="baz"
/>

If a component property can be placed on a row (if it is a property), it remains on the current row
<Foo bar="bar" />

// Multi-line attributes are indented
<Foo
  superLongParam="bar"
  anotherSuperLongParam="baz"
>
  <Quux />
</Foo>

/ / do not recommend
<Foo superLongParam="bar"
     anotherSuperLongParam="baz" />
Copy the code

4.3, quotes,

JSX attributes use double quotes, while other JS attributes use single quotes. Because JSX attributes cannot contain escaped quotes, it is more convenient to use double quotes when typing abbreviations such as “don’t”.

Recommendation:

<Foo bar="bar" />

<Foo style={{ left: '20px' }} />
Copy the code

Is not recommended:

<Foo bar='bar' />
    
<Foo style={{ left: "20px}} "/ >
Copy the code

5. Style writing

React styles can use inline style styles or use the className attribute to refer to CSS classes defined in external CSS stylesheets. We recommend using className to define styles. SCSS is recommended to replace the traditional CSS writing method. The specific writing method of SCSS to improve efficiency can be referred to the previous summarized article.

DefaultProps is defined using static properties

DefaultProps is recommended to be defined using static properties, not outside class.

Recommendation:

class Example extends React.Component {
  static defaultProps = {
    name: 'stranger'
  }

  render() {
   // ...}}Copy the code

Is not recommended:

class Example extends React.Component {
  render() {
    // ...
  }
}

Example.propTypes = {
  name: PropTypes.string
};
Copy the code

7. Set key properties

Key helps React identify which elements have changed, such as being added or removed. So you should give each element in the array a definite identity. As a last option, you can use the element index index as the key when the element id is not specified, but only if the order of the list items may change, and if you use the index as the key, as this can lead to poor performance and component state issues.

Recommendation:

{todos.map(todo= > (
  <Todo
    {. todo}
    key={todo.id}
  />
))}
Copy the code

Is not recommended:

{todos.map((todo, index) = ><Todo {... todo} key={index} /> )}Copy the code

Bind event handlers to components

React provides 4 methods for component binding event handlers, including public class fields syntax, binding in constructors, using arrow functions in callbacks, and using function.prototype. bind. We recommend using the public Class Fields syntax and using the arrow function notation (passing parameters to the event handler) when not required.

Recommendation:

 handleClick = () => {
    console.log('this is:', this);
 }
 <button onClick={this.handleClick}> Click me </button>
Copy the code

Is not recommended:

 constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
 }
 handleClick(){
    console.log('this is:', this);
 }
 <button onClick={this.handleClick}> Click me </button>
Copy the code

9, the State

9.1. Do not modify state directly

To change state anywhere other than state initialization, use the setState() method, otherwise the component will not be rerendered if it is assigned directly.

Recommendation:

this.setState({comment: 'Hello'});
Copy the code

Is not recommended:

this.state.comment = 'hello';
Copy the code

9.2 State updates may be asynchronous

React may combine multiple setState() calls into a single call for performance reasons; Because this.props and this.state might update asynchronously, this scenario requires setState() to receive a function instead of an object.

Recommendation:

this.setState((state, props) = > ({
  counter: state.counter + props.increment
}));
Copy the code

Is not recommended:

this.setState({
  counter: this.state.counter + this.props.increment,
});

Copy the code

10. Code sequence of components

Components should have a strict code order to facilitate code maintenance, and we recommend consistent code order in each component.

class Example extends Component {
    // Static attributes
    static defaultProps = {}

    // constructor
    constructor(props) {
        super(props);
        this.state={}
    }

    // Declare the periodic hook function
    // In the order in which they are executed
    // 1. componentWillMount
    // 2. componentWillReceiveProps
    // 3. shouldComponentUpdate
    // 4. componentDidMount
    // 5. componentDidUpdate
    // 6. componentWillUnmount
    componentDidMount() { ... }

    // Event function/normal function
    handleClick = (e) = >{... }// Finally, render methodrender() { ... }}Copy the code

11. Use advanced components

Use higher-order components to solve crosscutting concerns rather than mixins, which can be documented;

12, avoid unnecessary render

The shouldComponentUpdate hook function and the react. PureComponent class are both methods to avoid unnecessary render when state and props change. The shouldComponentUpdate hook function needs to implement its own shallow comparison logic manually, while the react. PureComponent class defaults to shallow comparisons between props and state and reduces the possibility of skipping necessary updates. We recommend using React.PureComponent to avoid unwanted render.

13. State improvement

If multiple components need to reflect the same change data, it is recommended that the shared state be promoted to the nearest common parent component. Instead of trying to synchronize state across different components, rely on top-down data flow.

14. Context is recommended

If a property is needed between components at different levels of the component tree, we should use Context to provide a way to share the property between components, rather than explicitly passing props through each layer of the component tree.

15. Refs

Refs provides a way to access DOM nodes or React elements created in the Render method. We recommend using Refs in the createRef API style or as a callback function rather than using this.refs.textinput as an outdated way to access Refs because it has some problems.

16. Route loading

It is recommended to use routing lazy to load content that the current user needs, which can significantly improve the performance of your application. While it doesn’t reduce the overall code volume of your application, you can avoid loading code that users never need, and reduce the amount of code that needs to be loaded during initial loading.

Recommendation:

const OtherComponent = React.lazy((a)= > import('./OtherComponent'));
Copy the code

Is not recommended:

import OtherComponent from './OtherComponent';
Copy the code

17. Timing of AJAX requests

It is recommended to make AJAX requests in the life cycle function componentDidMount. By doing so, you can take the data returned by the AJAX request and update the component with setState.

Hard to sort out for a long time, but also hope to manually praise encouragement ~

Making address:Click here to, if you like or have some inspiration, please help to give a star ~, to the author is also a kind of encouragement.

References:

1, github.com/Khan/style-…

2, segmentfault.com/a/119000001…