21 个整理 React 项目的最佳实践

共 10165字,需浏览 21分钟

 ·

2024-06-21 09:10




今天,我们将讨论一些改善React应用程序运行状况的最佳实践。


这些规则应用广泛。因此,拥有这些知识势在必行。


unsetunset1. 使用JSX速记unsetunset


尝试使用JSX速记来传递布尔变量。


举个例子,假设你想要控制导Navbar组件的标题可见性。



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


return(
  <Navbar showTitle />  
)

unsetunset2. 使用三元运算符unsetunset


假设你想要根据role显示用户的详细信息。



const { role } = user;

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



const { role } = user;

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

unsetunset3. 利用对象字面量unsetunset


对象字面量可以使代码更具可读性。


假设你想要根据role显示三种类型的用户。因为选项的数量超过两个,所以不能使用三元。



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

现在看上去是不是好多了?!


unsetunset4. 使用Fragmentunsetunset


始终使用Fragment而不是Div


Fragment可帮助保持代码干净,且有利于性能,因为在虚拟DOM中少创建了一个节点。



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


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

unsetunset5. 不要在渲染中定义函数unsetunset


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



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

unsetunset6. 使用Memounsetunset


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



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无关。


但是,每次单击按钮时,它都会呈现。



让我们将ChildComponent编辑为:


import React ,{useState} from "react";

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

现在,无论你单击多少次按钮,都仅在必要时渲染。


unsetunset7. JavaScript + CSSunsetunset


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



// CSS FILE

.body {
  height10px;
}

//JSX

return <div className='body'>

</div>


const bodyStyle = {
  height"10px"
}

return <div style={bodyStyle}>

</div>


unsetunset8. 使用对象解构unsetunset


假设你需要显示用户的详细信息,



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

unsetunset9.字符串prop不需要大括号unsetunset


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



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


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

unsetunset10. 从JSX删除JS代码unsetunset


将不能用于渲染或UI功能的JS代码移出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>

);

unsetunset11. 使用模板字面量unsetunset


使用模板字面量生成大字符串。避免使用字符串串联。这样会更干净。



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

unsetunset12. 按顺序导入unsetunset


始终按特定顺序导入内容。这样可提高代码可读性。



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





  • 内置



  • 外部



  • 内部


所以上面的例子变成了:


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

unsetunset13. 使用隐式返回unsetunset


使用JavaScript功能中的隐式return来编写漂亮的代码。


假设我们想要函数执行简单的计算并返回结果。



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


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

unsetunset14. 组件命名unsetunset


始终对组件应用PascalCase命名约定,对实例应用CamelCase命名约定。



import reservationCard from './ReservationCard';

const ReservationItem = <ReservationCard />;


import ReservationCard from './ReservationCard';

const reservationItem = <ReservationCard />;

unsetunset15. 保留prop命名unsetunset


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



<MyComponent style="dark" />

<MyComponent className="dark" />


<MyComponent variant="fancy" />

unsetunset16. 引号unsetunset


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



<Foo bar='bar' />

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


<Foo bar="bar" />

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

unsetunset17. prop命名unsetunset


prop命名使用camelCase,如果prop值是React组件,则使用PascalCase。



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


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

unsetunset18. 括号中的JSXunsetunset


如果组件跨越多行,记得用括号括起来。



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


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

);

unsetunset19. 自关闭标签unsetunset


如果组件没有任何子组件,则使用自结束标记。可提高可读性。



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


<SomeComponent variant="stuff" />

unsetunset20. 方法名称中的下划线unsetunset


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



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


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

unsetunset21. alt propunsetunset


始终在<img>标签中包含altprop。


并且不要在alt属性中使用pictureimage,因为屏幕阅读器已经将img元素宣布为图像。



<img src="hello.jpg" />

<img src="hello.jpg" alt="Picture of me rowing a boat" />


<img src="hello.jpg" alt="Me waving hello" />

unsetunset结论unsetunset


恭喜你,又学到了新的东西!


编程快乐!:D






浏览 202
1点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
1点赞
评论
收藏
分享

手机扫一扫分享

分享
举报