React 最佳实践
在开发 React App 时,遵循这些编码约定将为你带来更好的开发体验
强烈推荐 VS Code 作为 IDE
Visual Studio Code 拥有 React 开发者喜爱的多项功能。它提供了很多实用的扩展,可以优化开发环境。以下是一些 React 的实用扩展,它们可以在开发过程中为您提供帮助。
- Prettier
- ES Lint
- JavaScript(ES6)代码片段
- React.js 代码片段
- 自动导入
使用 ES6 语法
简洁的代码总是受人赞赏。在 JavaScript 中,你可以采用 ES6 语法来让你的代码更简洁。
编写箭头函数
// ES5
function getSum(a, b) {
return a + b;
}
// ES6
const getSum = (a, b) => a + b;
使用模板字符串
// ES5
var name = "Bilal";
console.log("My name is " + name);
// ES6
const name = "Bilal";
console.log(`My name is ${name}`);
使用const和let
它们具有块作用域。带有 的变量const
不能被更改,但带有 的let
变量是可变的
// ES5
var fruits = ["apple", "banana"];
// ES6
let fruits = ["apple", "banana"];
fruits.push("mango");
const workingHours = 8;
对象解构
var person = {
name: "John",
age: 40,
};
// ES5
var name = person.name;
var age = person.age;
// ES6
const { name, age } = person;
定义对象
var name = "John";
var age = 40;
var designations = "Full Stack Developer";
var workingHours = 8;
// ES5
var person = {
name: name,
age: age,
designation: designation,
workingHours: workingHours,
};
// ES6
const person = { name, age, designation, workingHours };
您将体验到 ES6 语法的诸多特性和灵活性
不要忘记JSX 中map的key Prop
key
从数组映射时,务必为每个 JSX 元素的 prop 赋一个唯一的值。阅读官方文档以加深理解。
const students = [{id: 1, name: 'Bilal'}, {id: 2, name: 'Haris'}];
// in return function of component
<ul>
{students.map(({id, name}) => (
<li key={id}>{name}</li>
))}
</ul>;
组件名称应采用PascalCase 命名
const helloText = () => <div>Hello</div>; // wrong
const HelloText = () => <div>Hello</div>; // correct
变量和函数名称应采用驼峰命名法
const working_hours = 10; // bad approach
const workingHours = 10; // good approach
const get_sum = (a, b) => a + b; // bad approach
const getSum = (a, b) => a + b; // good approach
ID 和类名应该采用短横线命名
<!--bad approach-->
<div className="hello_word" id="hello_world">Hello World</div>
<!--good approach -->
<div className="hello-word" id="hello-world">Hello World</div>
始终检查对象和数组是否为null和undefined
忽略对象null
和undefined
数组的情况可能会导致错误。
因此,请务必在代码中检查它们
const person = {
name: "Haris",
city: "Lahore",
};
console.log("Age", person.age); // error
console.log("Age", person.age ? person.age : 20); // correct
console.log("Age", person.age ?? 20); //correct
const oddNumbers = undefined;
console.log(oddNumbers.length); // error
console.log(oddNumbers.length ? oddNumbers.length : "Array is undefined"); // correct
console.log(oddNumbers.length ?? "Array is undefined"); // correct
避免内联样式
内联样式会使你的 JSX 代码变得混乱。建议在单独的.css
文件中使用类和 ID 来设置样式。
const text = <div style={{ fontWeight: "bold" }}>Happy Learing!</div>; // bad approach
const text = <div className="learning-text">Happy Learing!</div>; // good approach
在.css
文件中:
.learning-text {
font-weight: bold;
}
避免 DOM 操作
尝试使用 React 状态而不是 DOM 操作
错误的方法
<div id="error-msg">Please enter a valid value</div>
document.getElementById("error-msg").visibility = visible;
好方法
const [isValid, setIsValid] = useState(false);
<div hidden={isValid}>Please enter a valid value</div>;
isValid
在有验证值的逻辑时,设置为false 或 true
始终删除useEffect中的每个事件监听器
不要忘记编写清理函数来useEffect
删除之前添加的事件监听器
const printHello = () => console.log("HELLO");
useEffect(() => {
document.addEventListener("click", printHello);
return () => document.removeEventListener("click", printHello);
});
避免重复,使用通用组件
这是让你的代码更简洁的最好方法。为类似的元素组编写一个通用组件,并根据props
传递给它的参数进行渲染。
const Input=(props)=>{
const [inputValue, setInputValue]=useState('');
return(
<label>{props.thing}</label>
<input type='text' value={inputValue} onChange={(e)=>setInputValue(e.target.value)} />
)
}
在其他组件中,您可以使用Input
组件作为
<div>
<Input thing="First Name" />
<Input thing="Second Name" />
</div>
不要随意丢弃文件
将相关文件保存在同一个文件夹中,而不是将文件放在单个文件夹中。
例如,如果您想在 React 中创建导航栏,那么您应该创建一个文件夹并在其中放置.js
与.css
导航栏相关的文件
推荐使用函数式组件
如果您想渲染一些元素并且不需要使用状态,那么请使用功能组件而不是类组件,因为功能组件易于使用。
此外,如果您对React Hooks有所了解,那么使用功能组件您也可以轻松地处理状态。
养成编写辅助函数的习惯
有时您需要在 React App 中多次使用一个实用程序。
为了有效地处理这种情况,请在名为的单独文件中编写一个辅助函数helper-functions.js
,将其导入到您想要使用它的任何位置并在其中调用该函数。
使用三元运算符代替if/else if语句
使用if/else if
语句会使代码变得臃肿。尽量使用三元运算符,让代码更简洁。
// Bad approach
if (name === "Ali") {
return 1;
} else if (name === "Bilal") {
return 2;
} else {
return 3;
}
// Good approach
name === "Ali" ? 1 : name === "Bilal" ? 2 : 3;
使用index.js文件名来最小化导入的复杂性
index.js
如果您在名为的目录中有一个名为的文件actions
,并且想要在组件中导入其中的操作,则导入方式如下
import { actionName } from "src/redux/actions";
actions
目录路径在上面的 import 中已经解释过了。这里不需要像这样index.js
在 after 中提及actions
import { actionName } from "src/redux/actions/index";
Prop 的解构
如果你想摆脱一遍又一遍地写对象名来访问其属性,那么解构该对象是最好的解决方案。
假设你的组件接收一些值,例如name
、age
和designation
作为 props
// Bad approach
const Details = (props) => {
return (
<div>
<p>{props.name}</p>
<p>{props.age}</p>
<p>{props.designation}</p>
</div>
);
};
// Good approach
const Details = ({ name, age, designation }) => {
return (
<div>
<p>{name}</p>
<p>{age}</p>
<p>{designation}</p>
</div>
);
};
不要尝试在同一函数中访问已修改的状态变量
在函数中,如果你为状态变量赋值,那么即使在该函数中赋值后,你也无法访问该赋值
const Message = () => {
const [message, setMessage] = useState("Hello World");
const changeMessage = (messageText) => {
setMessage("Happy Learning");
console.log(message); // It will print Hello World on console
};
return <div>{message}</div>;
};
使用===运算符代替==
在比较两个值时,严格检查两个值及其数据类型是一种很好的做法。
"2" == 2 ? true : false; // true
"2" === 2 ? true : false; // false
现在就开始实践 React 中这些最佳的编码实践吧!
文章来源:https://dev.to/iambilalriaz/react-best-practices-ege