本文转载自:https://mp.weixin.qq.com/s/xvAJtv1RyOq7rBwaq_tm0Q
1. 使用 JSX 简写
尽量对布尔变量使用 JSX 简写。假设你想控制一个导航栏组件的标题可见性。
「不好的:」
1 2 3
| return ( <Navbar showTitle={true} /> );
|
「好的:」
1 2 3
| return ( <Navbar showTitle /> );
|
2. 使用三元运算符
假设你想根据角色显示用户详情。
「不好的:」
1 2 3 4 5 6 7
| const { role } = user;
if(role === ADMIN) { return <AdminUser /> } else { return <NormalUser /> }
|
「好的:」
1 2 3
| const { role } = user;
return role === ADMIN ? <AdminUser /> : <NormalUser />;
|
3. 利用对象字面量
对象字面量可以使我们的代码更具可读性。假设您要根据角色显示三种类型的用户。你不能使用三元运算符,因为选项数量超过两个。
「不好的:」
1 2 3 4 5 6 7 8 9 10
| const {role} = user;
switch(role) { case ADMIN: return <AdminUser />; case EMPLOYEE: return <EmployeeUser />; case USER: return <NormalUser />; }
|
「好的:」
1 2 3 4 5 6 7 8 9 10 11
| const {role} = user;
const components = { ADMIN: AdminUser, EMPLOYEE: EmployeeUser, USER: NormalUser };
const Component = components[role];
return <Component />;
|
现在看起来好多了。
4. 使用片段
尽量使用Fragment而不是Div。这使代码更简洁,对性能也有益,因为少创建一个虚拟 DOM 节点。
「不好的:」
1 2 3 4 5 6 7
| return ( <section> <Component1 /> <Component2 /> <Component3 /> </section> );
|
「好的:」
1 2 3 4 5 6 7
| return ( <> <Component1 /> <Component2 /> <Component3 /> </> );
|
5. 不要在 render 中定义函数
不要在 render 中定义函数。尽量使 render 中的逻辑最小化。
「不好的:」
1 2 3 4 5
| return ( <button onClick={() => dispatch(ACTION_TO_SEND_DATA)}> 这是一个不好的例子 </button> );
|
「好的:」
1 2 3 4 5 6 7
| const submitData = () => dispatch(ACTION_TO_SEND_DATA);
return ( <button onClick={submitData}> 这是一个好的例子 </button> );
|
6. 使用 useMemo
React.PureComponent 和 useMemo 可以显著提高应用程序的性能。它们帮助我们避免不必要的渲染。
「不好的:」
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import React, { useState } from "react";
export const TestMemo = () => { const [userName, setUserName] = useState("faisal"); const [count, setCount] = useState(0);
const increment = () => setCount(count + 1);
return ( <> <ChildrenComponent userName={userName} /> <button onClick={increment}>Increment</button> </> ); };
const ChildrenComponent =({userName}) => { console.log("rendered", userName); return <section>{userName}</section>; };
|
尽管 ChildComponent 的值与 count 无关,但它应该只渲染一次。但是,每次点击按钮时它都会重新渲染。
「好的:」
将 ChildrenComponent 改为:
1 2 3 4
| const ChildrenComponent = React.memo(({userName}) => { console.log("rendered"); return <section>{userName}</section>; });
|
现在,无论单击按钮多少次,它都只会在必要时重新渲染。
7. 将 CSS 写在 JavaScript 中
避免在编写 React 应用程序时使用纯 CSS,因为组织 CSS 比组织 JS 更加困难。
「不好的:」
1 2 3 4
| .body { height: 10px; }
|
1 2
| return <section className="body" />;
|
「好的:」
1 2 3 4 5
| const bodyStyle = { height: "10px" };
return <section style={bodyStyle} />;
|
8. 使用对象解构
充分利用对象解构。假设你需要显示一个用户的详细信息。
「不好的:」
1 2 3 4 5 6 7
| return ( <> <section>{user.name}</section> <section>{user.age}</section> <section>{user.profession}</section> </> );
|
「好的:」
1 2 3 4 5 6 7 8 9
| const { name, age, profession } = user;
return ( <> <section>{name}</section> <section>{age}</section> <section>{profession}</section> </> );
|
9. 字符串类型的 props 不需要花括号
当向子组件传递字符串类型的 props 时。
「不好的:」
1 2 3
| return ( <Navbar title={"My Special App"} /> );
|
「好的:」
1 2 3
| return ( <Navbar title="My Special App" /> );
|
10. 从 JSX 中提取 JS 代码
如果 JS 代码没有渲染或 UI 功能目的,请将其从 JSX 中提取出来。
「不好的:」
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| return ( <ul> {posts.map(post => ( <li onClick={event => { console.log(event.target, 'clicked!'); // <- 不好的 }} key={post.id} > {post.title} </li> ))} </ul> );
|
「好的:」
1 2 3 4 5 6 7 8 9 10 11 12 13
| const onClickHandler = event => { console.log(event.target, 'clicked!'); };
return ( <ul> {posts.map(post => ( <li onClick={onClickHandler} key={post.id}> {post.title} </li> ))} </ul> );
|
11. 使用模板字符串
使用模板字符串构建大型字符串。避免使用字符串连接。它很漂亮,也很简洁。
「不好的:」
1 2 3 4 5
| const userDetails = user.name + "'s profession is" + user.profession;
return ( <section>{userDetails}</section> );
|
「好的:」
1 2 3 4 5
| const userDetails = `${user.name}'s profession is ${user.profession}`;
return ( <section>{userDetails}</section> );
|
12. 按顺序导入
尽量按一定顺序导入东西。这提高了代码的可读性。
「不好的:」
1 2 3 4 5
| 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';
|
「好的:」
一个经验法则是保持导入顺序如下:
所以上面的例子变为:
1 2 3 4 5 6 7
| 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特性。假设你的函数进行一个简单的计算并返回结果。
「不好的:」
1 2 3
| const add = (a, b) => { return a + b; };
|
「好的:」
1
| const add = (a, b) => a + b;
|
14. 组件命名
组件始终使用 PascalCase,实例使用 camelCase。
「不好的:」
1 2 3
| import reservationCard from './ReservationCard';
const ReservationItem = <ReservationCard />;
|
「好的:」
1 2 3
| import ReservationCard from './ReservationCard';
const reservationItem = <ReservationCard />;
|
15. 保留的 prop 命名
不要在组件之间传递 props 时使用 DOM 组件的 prop 名称,因为其他人可能不期望这些名称。
「不好的:」
1 2 3
| <MyComponent style="dark" />
<MyComponent className="dark" />
|
「好的:」
1
| <MyComponent variant="fancy" />
|
16. 引号
JSX 属性使用双引号,其他所有 JS 使用单引号。
「不好的:」
1 2 3
| <Foo bar='bar' />
<Foo style={{ left: "20px" }} />
|
「好的:」
1 2 3
| <Foo bar="bar" />
<Foo style={{ left: '20px' }} />
|
17. prop 命名
始终使用 camelCase 作为 prop 名称,如果 prop 值为 React 组件,则使用 PascalCase。
「不好的:」
1 2 3 4
| <Component UserName="hello" phone_number={12345678} />
|
「好的:」
1 2 3 4 5
| <MyComponent userName="hello" phoneNumber={12345678} Component={SomeComponent} />
|
18. 把多行的 JSX 用括号包裹
如果组件跨多行,请始终将其包装在括号中。
「不好的:」
1 2 3
| return <MyComponent variant="long"> <MyChild /> </MyComponent>;
|
「好的:」
1 2 3 4 5
| return ( <MyComponent variant="long"> <MyChild /> </MyComponent> );
|
19. 使用自闭合标签
如果组件没有子元素,则使用自闭合标签。这提高了可读性。
「不好的:」
1
| <SomeComponent variant="stuff"></SomeComponent>
|
「好的:」
1
| <SomeComponent variant="stuff" />
|
20. 方法名中不要使用下划线
不要在任何内部 React 方法中使用下划线。
「不好的:」
1 2 3
| const _onClickHandler = () => { };
|
「好的:」
1 2 3
| const onClickHandler = () => { };
|
21. alt 属性
在**
标签中始终包含 alt 属性。并且不要在 alt 属性中使用picture或image**,因为屏幕阅读器已经将img元素宣布为图像。不需要包含它们。
「不好的:」
1 2 3
| <img src="hello.jpg" />
<img src="hello.jpg" alt="Picture of me waving hello" />
|
「好的:」
1
| <img src="hello.jpg" alt="Me waving hello" />
|