打造清洁 React 项目的 21 个最佳实践
要阅读更多类似的文章,请访问我的博客
React 对于事物的结构非常开放。正因如此,我们有责任保持项目的简洁和可维护。
今天,我们将讨论一些提升 React 应用程序健康状况的最佳实践。这些规则已被广泛接受。因此,掌握这些知识至关重要。
所有内容都将通过代码显示,所以系好安全带!
1. 使用 JSX 简写
尝试使用 JSX 简写来传递布尔变量。假设你想控制导航栏组件的标题可见性。
坏的
return (
  <Navbar showTitle={true} />
);
好的
return(
  <Navbar showTitle />  
)
2. 使用三元运算符
假设您想根据角色显示用户的详细信息。
坏的
const { role } = user;
if(role === ADMIN) {
  return <AdminUser />
}else{
  return <NormalUser />
} 
好的
const { role } = user;
return role === ADMIN ? <AdminUser /> : <NormalUser />
3. 利用对象字面量
对象字面量可以帮助提升代码的可读性。假设你想根据用户的角色显示三种类型的用户。你不能使用三元组,因为选项数量超过了两个。
坏的
const {role} = user
switch(role){
  case ADMIN:
    return <AdminUser />
  case EMPLOYEE:
    return <EmployeeUser />
  case USER:
    return <NormalUser />
}
好的
const {role} = user
const components = {
  ADMIN: AdminUser,
  EMPLOYEE: EmployeeUser,
  USER: NormalUser
};
const Component = components[role];
return <Componenent />;
现在看起来好多了。
4. 使用片段
始终使用Fragmentover Div。它使代码保持简洁,并且由于在虚拟 DOM 中少创建了一个节点,因此也有利于提高性能。
坏的
return (
  <div>
     <Component1 />
     <Component2 />
     <Component3 />
  </div>  
)
好的
return (
  <>
     <Component1 />
     <Component2 />
     <Component3 />
  </>  
)
5. 不要在 Render 内部定义函数
不要在 render 函数内部定义函数。尽量将 render 函数内部的逻辑控制在最低限度。
坏的
return (
    <button onClick={() => dispatch(ACTION_TO_SEND_DATA)}>    // NOTICE HERE
      This is a bad example 
    </button>  
)
好的
const submitData = () => dispatch(ACTION_TO_SEND_DATA)
return (
  <button onClick={submitData}>  
    This is a good example 
  </button>  
)
6.使用备忘录
React.PureComponent并且Memo可以显著提升应用程序的性能。它们帮助我们避免不必要的渲染。
坏的
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。但是,每次点击按钮时它都会渲染。
好的
让我们将其编辑ChildrenComponent如下:
import React ,{useState} from "react";
const ChildrenComponent = React.memo(({userName}) => {
    console.log('rendered')
    return <div> {userName}</div>
})
现在,无论您单击按钮多少次,它只会在必要时呈现。
7. 将 CSS 放入 JavaScript
编写 React 应用程序时避免使用原始 JavaScript,因为组织 CSS 比组织 JS 困难得多。
坏的
// CSS FILE
.body {
  height: 10px;
}
//JSX
return <div className='body'>
</div>
好的
const bodyStyle = {
  height: "10px"
}
return <div style={bodyStyle}>
</div>
8. 使用对象解构
充分利用对象解构。假设你需要显示用户的详细信息。
坏的
return (
  <>
    <div> {user.name} </div>
    <div> {user.age} </div>
    <div> {user.profession} </div>
  </>  
)
好的
const { name, age, profession } = user;
return (
  <>
    <div> {name} </div>
    <div> {age} </div>
    <div> {profession} </div>
  </>  
)
9. 字符串 props 不需要花括号
将字符串道具传递给子组件时。
坏的
return(
  <Navbar title={"My Special App"} />
)
好的
return(
  <Navbar title="My Special App" />  
)
10. 从 JSX 中删除 JS 代码
如果 JS 代码不用于任何渲染或 UI 功能,请将其移出 JSX。
坏的
return (
  <ul>
    {posts.map((post) => (
      <li onClick={event => {
        console.log(event.target, 'clicked!'); // <- THIS IS BAD
        }} key={post.id}>{post.title}
      </li>
    ))}
  </ul>
);
好的
const onClickHandler = (event) => {
   console.log(event.target, 'clicked!'); 
}
return (
  <ul>
    {posts.map((post) => (
      <li onClick={onClickHandler} key={post.id}> {post.title} </li>
    ))}
  </ul>
);
11. 使用模板字符串
使用模板字面量来构建大型字符串。避免使用字符串连接。这样简洁又美观。
坏的
const userDetails = user.name + "'s profession is" + user.proffession
return (
  <div> {userDetails} </div>  
)
好的
const userDetails = `${user.name}'s profession is ${user.proffession}`
return (
  <div> {userDetails} </div>  
)
12.按顺序导入
始终尝试按特定顺序导入内容。这可以提高代码的可读性。
坏的
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';
好的
经验法则是保持导入顺序如下:
- 
  内置 
- 
  外部的 
- 
  内部的 
因此上面的例子就变成:
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. 使用隐式返回
利用 JavaScript 的内置功能return编写优美的代码。假设你的函数执行了一个简单的计算并返回结果。
坏的
const add = (a, b) => {
  return a + b;
}
好的
const add = (a, b) => a + b;
14.组件命名
始终对组件使用 PascalCase,对实例使用 camelCase。
坏的
import reservationCard from './ReservationCard';
const ReservationItem = <ReservationCard />;
好的
import ReservationCard from './ReservationCard';
const reservationItem = <ReservationCard />;
15. 保留的 Prop 命名
不要使用 DOM 组件 prop 名称在组件之间传递 props,因为其他人可能不会想到这些名称。
坏的
<MyComponent style="dark" />
<MyComponent className="dark" />
好的
<MyComponent variant="fancy" />
16. 引言
对 JSX 属性使用双引号,对所有其他 JS 使用单引号。
坏的
<Foo bar='bar' />
<Foo style={{ left: "20px" }} />
好的
<Foo bar="bar" />
<Foo style={{ left: '20px' }} />
17.道具命名
如果 prop 值是 React 组件,则始终使用 camelCase 作为 prop 名称或使用 PascalCase。
坏的
<Component
  UserName="hello"
  phone_number={12345678}
/>
好的
<MyComponent
  userName="hello"
  phoneNumber={12345678}
  Component={SomeComponent}
/>
18. 括号中的 JSX
如果您的组件跨越多行,请始终将其括在括号中。
坏的
return <MyComponent variant="long">
           <MyChild />
         </MyComponent>;
好的
return (
    <MyComponent variant="long">
      <MyChild />
    </MyComponent>
);
19. 自闭合标签
如果你的组件没有任何子组件,那么请使用自闭合标签。它可以提高可读性。
坏的
<SomeComponent variant="stuff"></SomeComponent>
好的
<SomeComponent variant="stuff" />
20. 方法名称中的下划线
不要在任何内部 React 方法中使用下划线。
坏的
const _onClickHandler = () => {
  // do stuff
}
好的
const onClickHandler = () => {
  // do stuff
}
21. 替代道具
请务必在标签中添加 alt 属性<img >。不要在 alt 属性中使用picture或 ,因为屏幕阅读器已将元素识别为图像。无需添加。imagepropertyimg
坏的
<img src="hello.jpg" />
<img src="hello.jpg" alt="Picture of me rowing a boat" />
好的
<img src="hello.jpg" alt="Me waving hello" />
结论
好了。恭喜你读到这里!希望你从这篇文章中有所收获。
祝你度过美好的一天!:D
有话要说吗?
资源
通过LinkedIn或我的个人网站与我联系。
文章来源:https://dev.to/mohammadfaisal/21-best-practices-for-a-clean-react-project-jdf 后端开发教程 - Java、Spring Boot 实战 - msg200.com
            后端开发教程 - Java、Spring Boot 实战 - msg200.com
          