21 個(gè)整理 React 項(xiàng)目的最佳實(shí)踐
共 10165字,需瀏覽 21分鐘
·
2024-06-21 09:10
今天,我們將討論一些改善React應(yīng)用程序運(yùn)行狀況的最佳實(shí)踐。
這些規(guī)則應(yīng)用廣泛。因此,擁有這些知識勢在必行。
1. 使用JSX速記
嘗試使用JSX速記來傳遞布爾變量。
舉個(gè)例子,假設(shè)你想要控制導(dǎo)Navbar組件的標(biāo)題可見性。
壞
return (
<Navbar showTitle={true} />
);
好
return(
<Navbar showTitle />
)
2. 使用三元運(yùn)算符
假設(shè)你想要根據(jù)role顯示用戶的詳細(xì)信息。
壞
const { role } = user;
if(role === ADMIN) {
return <AdminUser />
}else{
return <NormalUser />
}
好
const { role } = user;
return role === ADMIN ? <AdminUser /> : <NormalUser />
3. 利用對象字面量
對象字面量可以使代碼更具可讀性。
假設(shè)你想要根據(jù)role顯示三種類型的用戶。因?yàn)檫x項(xiàng)的數(shù)量超過兩個(gè),所以不能使用三元。
壞
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 />;
現(xiàn)在看上去是不是好多了?!
4. 使用Fragment
始終使用Fragment而不是Div。
Fragment可幫助保持代碼干凈,且有利于性能,因?yàn)樵谔摂MDOM中少創(chuàng)建了一個(gè)節(jié)點(diǎn)。
壞
return (
<div>
<Component1 />
<Component2 />
<Component3 />
</div>
)
好
return (
<>
<Component1 />
<Component2 />
<Component3 />
</>
)
5. 不要在渲染中定義函數(shù)
不要在渲染中定義函數(shù)。盡量將渲染內(nèi)部的邏輯保持在最小。
壞
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. 使用Memo
React.PureComponent和Memo可以顯著提高應(yīng)用程序的性能,幫助我們避免不必要的渲染。
壞
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>;
};
盡管子組件應(yīng)該只呈現(xiàn)一次,因?yàn)?code style="color: rgb(155, 110, 35);font-size: 14px;line-height: 1.8em;letter-spacing: 0em;background: none 0% 0% / auto no-repeat scroll padding-box border-box rgb(255, 245, 227);width: auto;height: auto;margin-left: 2px;margin-right: 2px;padding: 2px 4px;border-style: none;border-width: 3px;border-color: rgb(0, 0, 0) rgba(0, 0, 0, 0.4) rgba(0, 0, 0, 0.4);border-radius: 4px;font-family: Operator Mono, Consolas, Monaco, Menlo, monospace;word-break: break-all;">count的值與ChildComponent無關(guān)。
但是,每次單擊按鈕時(shí),它都會呈現(xiàn)。
好
讓我們將ChildComponent編輯為:
import React ,{useState} from "react";
const ChildrenComponent = React.memo(({userName}) => {
console.log('rendered')
return <div> {userName}</div>
})
現(xiàn)在,無論你單擊多少次按鈕,都僅在必要時(shí)渲染。
7. JavaScript + CSS
在編寫React應(yīng)用程序時(shí)避免使用原始JavaScript,因?yàn)榻M織CSS比組織JS要困難得多。
壞
// CSS FILE
.body {
height: 10px;
}
//JSX
return <div className='body'>
</div>
好
const bodyStyle = {
height: "10px"
}
return <div style={bodyStyle}>
</div>
8. 使用對象解構(gòu)
假設(shè)你需要顯示用戶的詳細(xì)信息,
壞
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.字符串prop不需要大括號
在將字符串props傳遞給子組件時(shí),
壞
return(
<Navbar title={"My Special App"} />
)
好
return(
<Navbar title="My Special App" />
)
10. 從JSX刪除JS代碼
將不能用于渲染或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>
);
11. 使用模板字面量
使用模板字面量生成大字符串。避免使用字符串串聯(lián)。這樣會更干凈。
壞
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. 按順序?qū)?span style="align-items: unset;background-attachment: scroll;background-clip: border-box;background-image: none;background-origin: padding-box;background-position: 0% 0%;background-repeat: no-repeat;background-size: auto;border-style: none;border-width: 1px;border-color: rgb(0, 0, 0);border-radius: 0px;box-shadow: none;color: rgb(0, 0, 0);display: none;flex-direction: unset;float: unset;height: auto;justify-content: unset;letter-spacing: 0px;line-height: 1.5em;overflow: unset;text-indent: 0em;text-shadow: none;transform: none;width: auto;-webkit-box-reflect: unset;">unset
始終按特定順序?qū)雰?nèi)容。這樣可提高代碼可讀性。
好
經(jīng)驗(yàn)法則是保持這樣的導(dǎo)入順序:
-
內(nèi)置 -
外部 -
內(nèi)部
所以上面的例子變成了:
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來編寫漂亮的代碼。
假設(shè)我們想要函數(shù)執(zhí)行簡單的計(jì)算并返回結(jié)果。
壞
const add = (a, b) => {
return a + b;
}
好
const add = (a, b) => a + b;
14. 組件命名
始終對組件應(yīng)用PascalCase命名約定,對實(shí)例應(yīng)用CamelCase命名約定。
壞
import reservationCard from './ReservationCard';
const ReservationItem = <ReservationCard />;
好
import ReservationCard from './ReservationCard';
const reservationItem = <ReservationCard />;
15. 保留prop命名
不要使用DOM組件prop名稱在組件之間傳遞props,因?yàn)槠渌丝赡懿恍枰@些名稱。
壞
<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命名
prop命名使用camelCase,如果prop值是React組件,則使用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. 自關(guān)閉標(biāo)簽
如果組件沒有任何子組件,則使用自結(jié)束標(biāo)記??商岣呖勺x性。
壞
<SomeComponent variant="stuff"></SomeComponent>
好
<SomeComponent variant="stuff" />
20. 方法名稱中的下劃線
不要在任何內(nèi)部React方法中使用下劃線。
壞
const _onClickHandler = () => {
// do stuff
}
好
const onClickHandler = () => {
// do stuff
}
21. alt prop
始終在<img>標(biāo)簽中包含altprop。
并且不要在alt屬性中使用picture或image,因?yàn)槠聊婚喿x器已經(jīng)將img元素宣布為圖像。
壞
<img src="hello.jpg" />
<img src="hello.jpg" alt="Picture of me rowing a boat" />
好
<img src="hello.jpg" alt="Me waving hello" />
結(jié)論
恭喜你,又學(xué)到了新的東西!
編程快樂!:D
