20个Clean Code 最佳实践,完善你的React 项目!

1,087 阅读4分钟

今天,我们将讨论一些可遵循的最佳实践,以改善您的 React 应用程序健康状况。 这些规则被广泛接受。 因此,掌握这些知识是很有必要的。

1.使用JSX 简写

使用 JSX 来传递布尔变量。 假设您想控制“Navbar”组件的标题可见性。

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

始终在 Div 上使用 Fragment。它保持代码干净,也有利于提高性能,因为在虚拟 DOM 中创建的节点少了一个

bad

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

good

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

5.不要定义渲染内部的函数

不要在渲染内部定义函数。尽量将内部逻辑渲染保持在绝对最小值。

bad

return (
    <button onClick={() => dispatch(ACTION_TO_SEND_DATA)}>    // NOTICE HERE
      This is a ### bad example 
    </button>  
)

good

const submitData = () => dispatch(ACTION_TO_SEND_DATA)

return (
  <button onClick={submitData}>  
    This is a ### good example 
  </button>  
)

6.使用memo

React.PureComponentMemo 可以显着提高应用程序的性能。它们帮助我们避免不必要的渲染。

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.将CSS放入JavaScript中

在编写 React 应用程序时,尽量避免原始 JavaScript,因为组织 CSS 比组织 JS 困难得多。

bad

// CSS FILE

.body {
  height: 10px;
}

//JSX

return <div className='body'>
   
</div>

good

const bodyStyle = {
  height: "10px"
}

return <div style={bodyStyle}>

</div>

8.使用对象析构

使用对象析构对您有利。假设您需要显示用户的详细信息。

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>
  </>  
)

9.string 类型的props无需使用花括弧

将字符串props传递给子组件时。

bad

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

good

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

10. 从JSX中删除JS代码

如果任何JS代码没有用于渲染或用户界面功能,则将任何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>
);

11.使用模板文字

使用模板文字来构建大字符串。避免使用字符串串联。它很好,也很干净。

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>  
)

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

return (

{userDetails}
) ```

12.有序的import

总是尝试按一定顺序导入东西。它提高了代码的可读性。

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

经验法则是这样保持导入顺序:

  1. 内置
  2. 外部
  3. 内部

所以上面的例子变成了:

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';

13.使用隐式return

使用隐式 return 的 JavaScript 特性来编写漂亮的代码。假设你的函数做了一个简单的计算并返回结果。

bad

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

good

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

14.组件命名

始终使用PascalCase作为组件,为实例使用骆驼Case。

bad

import reservationCard from './ReservationCard';

const ReservationItem = <ReservationCard />;

good

import ReservationCard from './ReservationCard';

const reservationItem = <ReservationCard />;

15.保留props名称

不要使用DOM组件props名在组件之间传递props,因为其他人可能不会期望这些名称。

bad

<MyComponent style="dark" />

<MyComponent className="dark" />

good

<MyComponent variant="fancy" />

16.引号

JSX属性使用双引号,所有其他JS使用单引号。

bad

<Foo bar='bar' />

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

good

<Foo bar="bar" />

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

17.props命名

如果道具值是React组件,则始终使用骆驼壳作为道具名称或PascalCase。

bad

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

good

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

18.括号中的JSX

如果您的组件跨越多行,请始终将其包裹在括号中.

bad

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

good

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

19.自闭标签

如果您的组件没有任何子组件,请使用自闭标签。它提高了可读性。

bad

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

good

<SomeComponent variant="stuff" />

20.方法名称中的下划线

在任何内部React方法中不要使用下划线

bad

const _onClickHandler = () => {
  // do stuff
}

good

const onClickHandler = () => {
  // do stuff
}

最后

❤️ 看完三件事:

如果你觉得这篇内容对你挺有启发,我想邀请你帮我个小忙:

  1. 点赞,让更多的人也能看到这篇内容,也方便自己随时找到这篇内容(收藏不点赞,都是耍流氓 -_-);
  2. 关注我们,不定期分好文章;
  3. 也看看其它文章;

🎉欢迎你把自己的学习体会写在留言区,与我和其他同学一起讨论。如果你觉得有所收获,也欢迎把文章分享给你的朋友。