5個技巧助你編寫更好的React代碼
在本文中,我想分享幾個技巧,這些技巧將改善你的React代碼。
1. 解構(gòu) props
在 JS 中解構(gòu)對象(尤其是 props)可以大大減少代碼中的重復(fù)??聪旅娴睦樱?coffeecard coffee="{item}" key="{item.id}">
- //Parent Component
- import React from 'react';
- import CoffeeCard from './CoffeeCard';
- const CafeMenu = () => {
- const coffeeList = [
- {
- id: '0',
- name: 'Espresso',
- price: '2.00',
- size: '16'
- },
- {
- id: '1',
- name: 'Cappuccino',
- price: '3.50',
- size: '24'
- },
- {
- id: '2',
- name: 'Caffee Latte',
- price: '2.70',
- size: '12'
- }
- ];
- return coffeeList.map(item => (
- <CoffeeCard key={item.id} coffee={item} />
- ));
- };
- export default CafeMenu;
CafeMenu 組件用于存儲可用飲料的列表,現(xiàn)在我們想要創(chuàng)建另一個可以顯示一種飲料的組件。如果不對 props 進行解構(gòu),我們的代碼將像下面這樣:
- //Child Component
- import React from 'react';
- const CoffeeCard = props => {
- return (
- <div>
- <h1>{props.coffee.name}</h1>
- <p>Price: {props.coffee.price}$</p>
- <p>Size: {props.coffee.size} oz</p>
- </div>
- );
- };
- export default CoffeeCard;
如你所見,它看起來并不好,每次我們需要獲取某個屬性時,都要重復(fù) props.coffee,幸運的是,我們可以通過解構(gòu)來簡化它。
- //Child Component (after destructuring props)
- import React from 'react';
- const CoffeeCard = props => {
- const { name, price, size } = props.coffee;
- return (
- <div>
- <h1>{name}</h1>
- <p>Price: {price}$</p>
- <p>Size: {size} oz</p>
- </div>
- );
- };
- export default CoffeeCard;
如果我們想將大量參數(shù)傳遞給子組件,我們還可以直接在構(gòu)造函數(shù)(或函數(shù)組件的參數(shù))中解構(gòu) props。比如:
- //Parent Component
- import React from 'react';
- import ContactInfo from './ContactInfo';
- const UserProfile = () => {
- const name = 'John Locke';
- const email = 'john@locke.com';
- const phone = '01632 960668';
- return <ContactInfo name={name} email={email} phone={phone} />;
- };
- export default UserProfile;
- //Child Component
- import React from 'react';
- const ContactInfo = ({ name, email, phone }) => {
- return (
- <div>
- <h1>{name}</h1>
- <p> E-mail: {email}</p>
- <p> Phone: {phone}</p>
- </div>
- );
- };
- export default ContactInfo;
2. 保持導(dǎo)入模塊的順序
有時(尤其是在“容器組件”中),我們需要使用許多不同的模塊,并且組件導(dǎo)入看上去有些混亂,如:
- import { Auth } from 'aws-amplify';
- import React from 'react';
- import SidebarNavigation from './components/SidebarNavigation';
- import { EuiPage, EuiPageBody } from '@elastic/eui';
- import { keyCodes } from '@elastic/eui/lib/services';
- import './index.css'
- import HeaderNavigation from './components/HeaderNavigation';
- import Routes from './Routes';
關(guān)于導(dǎo)入模塊的理想順序有很多不同的觀點。我建議多參考,然后找到適合你自己的那種。
至于我自己,我通常按類型對導(dǎo)入進行分組,并按字母順序?qū)λ鼈冞M行排序(這是可選操作)。我也傾向于保持以下順序:
- 標(biāo)準(zhǔn)模塊
- 第三方模塊
- 自己代碼導(dǎo)入(組件)
- 特定于模塊的導(dǎo)入(例如CSS,PNG等)
- 僅用于測試的代碼
快速重構(gòu)一下,我們的模塊導(dǎo)入看上去舒服多了了。
- import React from 'react';
- import { Auth } from 'aws-amplify';
- import { EuiPage, EuiPageBody } from '@elastic/eui';
- import { keyCodes } from '@elastic/eui/lib/services';
- import HeaderNavigation from './components/HeaderNavigation';
- import SidebarNavigation from './components/SidebarNavigation';
- import Routes from './Routes';
- import './index.css'
3.使用 Fragments
在我們的組件中,我們經(jīng)常返回多個元素。一個 React 組件不能返回多個子節(jié)點,因此我們通常將它們包裝在 div 中。有時,這樣的解決方案會有問題。比如下面的這個例子中:
我們要創(chuàng)建一個 Table 組件,其中包含一個 Columns 組件。
- import React from 'react';
- import Columns from './Columns';
- const Table = () => {
- return (
- <table>
- <tbody>
- <tr>
- <Columns />
- </tr>
- </tbody>
- </table>
- );
- };
- export default Table;
Columns 組件中包含一些 td 元素。由于我們無法返回多個子節(jié)點,因此需要將這些元素包裝在 div 中。
- import React from 'react';
- const Columns = () => {
- return (
- <div>
- <td>Hello</td>
- <td>World</td>
- </div>
- );
- };
- export default Columns;
然后就報錯了,因為tr 標(biāo)簽中不能放置 div。我們可以使用 Fragment 標(biāo)簽來解決這個問題,如下所示:
- import React, { Fragment } from 'react';
- const Columns = () => {
- return (
- <Fragment>
- <td>Hello</td>
- <td>World</td>
- </Fragment>
- );
- };
- export default Columns;
我們可以將 Fragment 視為不可見的 div。它在子組件將元素包裝在標(biāo)簽中,將其帶到父組件并消失。
你也可以使用較短的語法,但是它不支持 key 和屬性。
- import React from 'react';
- const Columns = () => {
- return (
- <>
- <td>Hello</td>
- <td>World</td>
- </>
- );
- };
- export default Columns;
4. 使用展示組件和容器組件
將應(yīng)用程序的組件分為展示(木偶)組件和容器(智能)組件。如果你不知道這些是什么,可以下面的介紹:
展示組件
- 主要關(guān)注UI,它們負(fù)責(zé)組件的外觀。
- 數(shù)據(jù)由 props 提供,木偶組件中不應(yīng)該調(diào)用API,這是智能組件的工作
- 除了UI的依賴包,它們不需要依賴應(yīng)用程序
- 它們可能包括狀態(tài),但僅用于操縱UI本身-它們不應(yīng)存儲應(yīng)用程序數(shù)據(jù)。
木偶組件有:加載指示器,模態(tài),按鈕,輸入。
容器組件
- 它們不關(guān)注樣式,通常不包含任何樣式
- 它們用于處理數(shù)據(jù),可以請求數(shù)據(jù),捕獲更改和傳遞應(yīng)用程序數(shù)據(jù)
- 負(fù)責(zé)管理狀態(tài),重新渲染組件等等
- 可能依賴于應(yīng)用程序,調(diào)用 Redux,生命周期方法,API和庫等等。
使用展示組件和容器組件的好處
- 更好的可讀性
- 更好的可重用性
- 更容易測試
此外,它還符合“單一責(zé)任原則” - 一個組件負(fù)責(zé)外觀,另一個組件負(fù)責(zé)數(shù)據(jù)。
示例
讓我們看一個簡單的例子。這是一個 BookList 組件,該組件可從API獲取圖書數(shù)據(jù)并將其顯示在列表中。
- import React, { useState, useEffect } from 'react';
- const BookList = () => {
- const [books, setBooks] = useState([]);
- const [isLoading, setLoading] = useState(false);
- useEffect(() => {
- setLoading(true);
- fetch('api/books')
- .then(res => res.json())
- .then(books => {
- setBooks(books);
- setLoading(false);
- });
- }, []);
- const renderLoading = () => {
- return <p>Loading...</p>;
- };
- const renderBooks = () => {
- return (
- <ul>
- {books.map(book => (
- <li>{book.name}</li>
- ))}
- </ul>
- );
- };
- return <>{isLoading ? renderLoading() : renderBooks()}</>;
- };
- export default BookList;
該組件的問題在于,它負(fù)責(zé)太多事情。它獲取并呈現(xiàn)數(shù)據(jù)。它還與一個特定的接口關(guān)聯(lián),因此在不復(fù)制代碼的情況下,不能使用此組件顯示特定用戶的圖書列表。
現(xiàn)在,讓我們嘗試將此組件分為展示組件和容器組件。
- import React from 'react';
- const BookList = ({ books, isLoading }) => {
- const renderLoading = () => {
- return <p>Loading...</p>;
- };
- const renderBooks = () => {
- return (
- <ul>
- {books.map(book => (
- <li key={book.id}>{book.name}</li>
- ))}
- </ul>
- );
- };
- return <>{isLoading ? renderLoading() : renderBooks()}</>;
- };
- export default BookList;
- import React, { useState, useEffect } from 'react';
- import BookList from './BookList';
- const BookListContainer = () => {
- const [books, setBooks] = useState([]);
- const [isLoading, setLoading] = useState(false);
- useEffect(() => {
- setLoading(true);
- fetch('/api/books')
- .then(res => res.json())
- .then(books => {
- setBooks(books);
- setLoading(false);
- });
- }, []);
- return <BookList books={books} isLoading={isLoading} />;
- };
- export default BookListContainer;
5. 使用 styled-components
對 React 組件進行樣式設(shè)置一直是個難題。查找拼寫錯誤的類名,維護大型 CSS 文件,處理兼容性問題有時可能很痛苦。
styled-components 是一個常見的 css in js 類庫,和所有同類型的類庫一樣,通過 js 賦能解決了原生 css 所不具備的能力,比如變量、循環(huán)、函數(shù)等。
要開始使用 styled-components,你需要首先安裝依賴:
- npm i styled-components
下面是一個示例:
- import React from 'react';
- import styled from 'styled-components';
- const Grid = styled.div`
- display: flex;
- `;
- const Col = styled.div`
- display: flex;
- flex-direction: column;
- `;
- const MySCButton = styled.button`
- background: ${props => (props.primary ? props.mainColor : 'white')};
- color: ${props => (props.primary ? 'white' : props.mainColor)};
- display: block;
- font-size: 1em;
- margin: 1em;
- padding: 0.5em 1em;
- border: 2px solid ${props => props.mainColor};
- border-radius: 15px;
- `;
- function App() {
- return (
- <Grid>
- <Col>
- <MySCButton mainColor='#ee6352' primary>My 1st Button</MySCButton>
- <MySCButton mainColor='#ee6352'>My 2st Button</MySCButton>
- <MySCButton mainColor='#ee6352'>My 3st Button</MySCButton>
- </Col>
- <Col>
- <MySCButton mainColor='#515052' primary>My 4st Button</MySCButton>
- <MySCButton mainColor='#515052'>My 5st Button</MySCButton>
- <MySCButton mainColor='#515052'>My 6st Button</MySCButton>
- </Col>
- </Grid>
- );
- }
- export default App;
這只是樣式化組件如何工作的一個簡單示例,但是它們可以做的還遠遠不止這些。你可以在其官方文檔中了解有關(guān)樣式化組件的更多信息。