查看原文
其他

如何编写干净的 React 代码?

CUGGZ 前端充电宝 2022-07-21

今天来看一些编写干净 React 代码的实用技巧!

1简化布尔类型 prop

如果组件的 prop 是一个布尔值,可以简写。

Bad:

return (
  <Navbar showTitle={true} />
);

Good:

return(
  <Navbar showTitle />  
)

2使用三元运算符

如果想要根据角色显示特定用户的详细信息,可以使用三元运算符来简化代码。

Bad:

const { role } = user;

if (role === ADMIN) {
  return <AdminUser />
else {
  return <NormalUser />

Good:


const { role } = user;

return role === ADMIN ? <AdminUser /> : <NormalUser />

3使用对象字符串

如果想根据角色来显示三种类型的用户,可以使用对象字符串,其有助于提高代码的可读性。

Bad:

const {role} = user

switch(role){
  case ADMIN:
    return <AdminUser />
  case EMPLOYEE:
    return <EmployeeUser />
  case USER:
    return <NormalUser />
}

Good:

const {role} = user

const components = {
  ADMIN: AdminUser,
  EMPLOYEE: EmployeeUser,
  USER: NormalUser
};

const Component = components[role];

return <Componenent />;

4使用 Fragments

由于 React 只能有一个根节点,所以尽可能使用 Fragment 而不是 div。它可以保持代码的整洁,并且有利于提高性能,因为在虚拟DOM中少创建一个节点。

Bad:

return (
  <div>
     <Component1 />
     <Component2 />
     <Component3 />
  </div>
  
)

Good:

return (
  <>
     <Component1 />
     <Component2 />
     <Component3 />
  </>
  
)

5不要在 Render 中定义函数

尽量将 render 中的逻辑减少,不要在 render 中定义函数。

Bad:

return (
    <button onClick={() => dispatch(ACTION_TO_SEND_DATA)}>
      bad
    </button>
  
)

Good:

const submitData = () => dispatch(ACTION_TO_SEND_DATA)

return (
  <button onClick={submitData}>  
    good
  </button>
  
)

6使用 Memo

使用 Memo 可以避免不必要的渲染,显著提高应用程序的性能。

Bad:

import React, { useState } from "react";

export const TestMemo = () => {
  const [userName, setUserName] = useState("faisal");
  const [count, setCount] = useState(0);
  
  const increment = () => setCount((count) => count + 1);
  
  return (
    <>
      <ChildrenComponent userName={userName} />
      <button onClick={increment}> Increment </button>
    </>

  );
};

const ChildrenComponent =({ userName }) => {
  console.log("rendered", userName);
  return <div> {userName} </div>;
};

理论上,子组件应该只渲染一次,因为count的值没有在ChildComponent组件使用。但是,它会在每次单击按钮时重新渲染。

Good:

import React ,{useState} from "react";

const ChildrenComponent = React.memo(({userName}) => {
    console.log('rendered')
    return <div> {userName}</div>
})

现在,无论点击多少次按钮,它都只会在必要时渲染。

7使用对象解构

如果想显示用户的详细信息。可以使用对象的解构。

Bad:

return (
  <>
    <div> {user.name} </div>
    <div> {user.age} </div>
    <div> {user.profession} </div>
  </>
  
)

Good:

const { name, age, profession } = user;

return (
  <>
    <div> {name} </div>
    <div> {age} </div>
    <div> {profession} </div>
  </>
  
)

8字符串类型的 prop 不需要花括号

在将字符串类型的 prop 传递给子组件时,不需要使用花括号包裹:

Bad:

return(
  <Navbar title={"App"} />
)

Good:

return(
  <Navbar title="App" />  
)

9从JSX中删除JS代码

如果JSX不能提供任何渲染或者UI功能,可以将JS代码移出JSX。

Bad:

return (
  <ul>
    {posts.map((post) => (
      <li onClick={event => {
        console.log(event.target, 'clicked!'); // <- THIS IS BAD
        }} key={post.id}>{post.title}
      </li>
    ))}
  </ul>
);

Good:

const onClickHandler = (event) => {
   console.log(event.target, 'clicked!'); 
}

return (
  <ul>
    {posts.map((post) => (
      <li onClick={onClickHandler} key={post.id}> {post.title} </li>
    ))}
  </ul>

);

10使用模板字符串

避免使用字符串拼接,而使用模板字符串来构建长字符串。

Bad:

const userDetails = user.name + "'s profession is" + user.proffession

return (
  <div> {userDetails} </div>  
)

Good:


const userDetails = `${user.name}'s profession is ${user.proffession}`

return (
  <div> {userDetails} </div>  
)

11按顺序导入

按一定的顺序导入内容,这样可以提高代码的可读性。

Bad:

import React from 'react';
import ErrorImg from '../../assets/images/error.png';
import styled from 'styled-components/native';
import colors from '../../styles/colors';
import { PropTypes } from 'prop-types';

Good:

import React from 'react';

import { PropTypes } from 'prop-types';
import styled from 'styled-components/native';

import ErrorImg from '../../assets/images/error.png';
import colors from '../../styles/colors';

12箭头函数

假设函数做了一个简单的计算并返回结果,可以简化箭头函数。

Bad:

const add = (a, b) => {
  return a + b;
}

Good:

const add = (a, b) => a + b;

13组件命名

使用 PascalCase 这种形式来给组件命名。

Bad:

import reservationCard from './ReservationCard';

const ReservationItem = <ReservationCard />;

Good:

import ReservationCard from './ReservationCard';

const reservationItem = <ReservationCard />;

14保留 prop 命名

不要使用 DOM 组件的 prop 名称在组件之间传递参数

Bad:

<MyComponent style="dark" />

<MyComponent className="dark" />

Good:

<MyComponent variant="fancy" />

15引号

对 JSX 属性使用双引号,对其他 JavaScript 代码使用单引号。

Bad:

<Foo bar='bar' />

<Foo style={{ left: "20px" }} />

Good:

<Foo bar="bar" />

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

16Prop 命名

如果 prop 的值是一个 React 组件,则 prop 名称使用 camelCase 或 PascalCase 的形式。

Bad:

<Component
  UserName="hello"
  phone_number={12345678}
/>

Good:

<MyComponent
  userName="hello"
  phoneNumber={12345678}
  Component={SomeComponent}
/>

17将 JSX 放在括号中

如果组件超过一行,就将其用括号括起来。

Bad:

return <MyComponent variant="long">
         <MyChild />
       </MyComponent>
;

Good:

return (
    <MyComponent variant="long">
      <MyChild />
    </MyComponent>

);

18自闭合标签

如果组件没有任何子级,则使用自闭合标签,这样可以提高代码可读性。

Bad:

<SomeComponent variant="stuff"></SomeComponent>

Good:

<SomeComponent variant="stuff" />

19方法中的下划线

不要在 React 内部的方法中使用下划线。

Bad:

const _onClickHandler = () => {
  // ...
}

Good:

const onClickHandler = () => {
  // ...
}

20alt 属性

在 img 标签中始终使用 alt 属性。

Bad:

<img src="hello.jpg" />

Good:

<img src="hello.jpg" alt="description" />


往期推荐

前端周刊 | 阿里云盘将推出VIP会员; 程序员做饭指南霸榜GitHub; Microsoft Edge即将超越 Safari

理解 TypeScript 的 never 类型

如何编写高性能的 React 代码:规则、模式、注意事项

21道 LeetCode 题解带你搞懂动态规划!

最佳 React UI 组件库,前端开发必备!


您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存