[譯]提高你react和js編碼的5個技巧

原文地址: dev.to/adancarrasc…

原文做者:Adán Carrasco前端

譯者:花花小仙女node

爲了保證可讀性,本文采用意譯而非直譯。另外,本文版權歸原做者全部,翻譯僅用於學習。轉載請聯繫做者。react

兩週前,我開始作一個新項目,有些代碼已經寫好了。然而,沒有最佳實踐可遵循。當你開始作一個新項目時,重要的是一塊兒定義基礎和最佳實踐/指南,團隊將遵循此基礎來編寫最佳代碼:可維護,易讀,易於理解。ios

我將描述我在項目中看到的5種狀況以及如何改進它們。axios

關鍵字:一致api

1.導入模塊的順序

以有組織的方式引入ES6模塊將節省你查找任何找不到或不須要模塊的時間。bash

以前微信

import { DatePicker } from '../../components'
import axios from 'axios'
import { IUser } from '../../models/User'
import React from 'react'
import { toCamelCase } from '../utils'
import { Button } from '@material-ui/core'複製代碼

以後
async

// node_modules
import React from 'react'
import { Button } from '@material-ui/core'
import axios from 'axios'

// Local modules
import { DatePicker } from '../../components'
import { toCamelCase } from '../utils'

// Types + Interfaces
import { IUser } from '../../models/User'複製代碼

以前的引入是無序的,一個文件可能不會太亂,可是當你打開大量文件時候,嘗試找到一個特定的包真的很難。咱們團隊達成一致,使用以後一種方式對導入的包進行分組,經過空格行分割每一個模塊。由於文件將保持一致,就能夠刪除註釋了。學習

2.儘量使用解構

另一個重要的事情就是防止沒必要要的嵌套和重複。在大多數狀況下,將大大提高可讀性。

以前

const UserProfile = props => (<div>
    <span>{props.firstName}</span>
    <span>{props.lastName}</span>
    <img src={props.profilePhoto}/>
  </div>)複製代碼

以後

const UserProfile = ({ firstName, lastName, profilePhoto }) =>
  (<div>
    <span>{firstName}</span>
    <span>{lastName}</span>
    <img src={profilePhoto}/>
  </div>)複製代碼

3.變量和方法的命名約定

關於代碼,有一點很重要,就是要知道一個方法將返回什麼,或者經過變量名輕鬆理解變量的含義(變量語義化),好比

以前

let User = {}
User.car = true
User.admin = true

function NewUser() {
  return User
}

function add_photo(photo) {
  user.photo = photo
}
複製代碼

以後

let user = {}
user.hasCar = true
user.isAdmin = true

function getUser() {
  return user
}

function setUserPhoto(photoUrl) {
  user.photoUrl = photoUrl
}複製代碼

以後展現瞭如何在命名變量和方法保持一致性,在如下方面保持一致:

  • 對於布爾類型使用:is, has,should作前綴
  • 對於方法使用 get/set 作前綴若是是操做 props
  • 變量和方法都使用駝峯命名

4.爲你的組件接收公共變量作好準備

以前

const UserProfile = props => {
  const { firstName, lastName, profilePhoto } = props
  return (<div>
    <span>{firstName}</span>
    <span>{lastName}</span>
    <img src={profilePhoto}/>
  </div>)
}複製代碼

以後

const UserProfile = props => {
  const { firstName, lastName, profilePhoto, ...rest} = props
  return (<div {...rest}>
    <span>{firstName}</span>
    <span>{lastName}</span>
    <img src={profilePhoto}/>
  </div>)
}複製代碼

以後,組件爲注入一些公共變量作準備,好比style, className, key等等,使用展開操做,將一組公共屬性傳入容器。

5.啞組件(dumb components)讓開發更簡單

建立啞組件(dumb components)而且遵循單一職責原則(Single Responsibility Principle)可讓你輕鬆建立和貢獻代碼,並保持代碼庫的整潔。

以前

import axios from 'axios'

const UserProfile = props => {
  const [user, setUser] = React.useState(null);
  React.useEffect(() => {
    getUser();
  }, []);

  async function getUser() {
    try {
      const user = await axios.get('/user/25')
    } catch(error) {
      console.error(error)
    }

    if(user.country === "DE") {
      user.flag = "/de-flag.png"
    } else if(user.country === "MX") {
      user.flag = "/mx-flag.png"
    }
    setUser(user);
  }

  const { firstName, lastName, profilePhoto, userFlag} = user

  return (<div>
    <span>{firstName}</span>
    <span>{lastName}</span>
    <img src={profilePhoto}/>
    <img src={userFlag}>
  </div>)
}複製代碼

以後

哪些可能會致使問題?

在組件裏添加業務邏輯( Business Logic )會讓它變得很難維護,調試和測試。個人建議是讓你的組件做爲展現組件(presentational component)。這樣,你能夠獨立出業務邏輯,而後專一於獨立地測試該組件。前面的每一個邏輯都混在一塊兒。如今咱們把每一個職責分開,這樣更容易測試和調試。

// UserProfilePage.jsx
// 操做全部的UserProfilePage相關,添加任何額外的props或業務邏輯

import { fetchUser } from '../api'

const UserProfilePage = props => {
  const [user, setUser] = React.useState(null);
  React.useEffect(() => {
    getUser();
  }, []);

  async function getUser() {
    const user = fetchUser(error => console.error(error))
    if(user.country === "DE") {
      user.flag = "/de-flag.png"
    } else if(user.country === "MX") {
      user.flag = "/mx-flag.png"
    }
    setUser(user);
  }
  return <UserProfile {...user}/>
}

// API.js
// 獲取數據並處理錯誤

export const fetchUser = async (errorHandler) => {
  try {
    const user = await axios.get('/user/25')
    retrun user
  } catch(error) {
    errorHandler(error)
  }
}

// UserProfile.jsx
// UserProfile.jsx以下

const UserProfile = props => {
  const { firstName, lastName, profilePhoto, ...rest} = props
  return (<div {...rest}>
    <span>{firstName}</span>
    <span>{lastName}</span>
    <img src={profilePhoto}/>
  </div>)
}
複製代碼


附加:若是你正在使用類型檢查器,請讓它發揮做用。

若是你的團隊選擇使用類型檢查器,那麼使用嚴格模式很重要,以確保它能發揮做用,來達到使用它的目的。

以前

const UserProfile = (props: any) => {
  const { firstName, lastName, profilePhoto, shouldShowPhoto } = props
  return (<div>
    <span>{firstName}</span>
    <span>{lastName}</span>
    <img src={profilePhoto}/>
  </div>)
}複製代碼

以後

interface IUserProfile {
  firstName: string
  lastName: string
  profilePhoto: string
  shouldShowPhoto?: boolean
}

const UserProfile = (props: IUserProfile) => {
  const { firstName, lastName, profilePhoto, shouldShowPhoto } = props
  return (<div>
    <span>{firstName}</span>
    <span>{lastName}</span>
    {shouldShowPhoto && <img src={profilePhoto}/>}
  </div>)
}複製代碼

我並非說這些規則適用於全部項目,但你的團隊須要制定本身的而且達成統一。

​你有哪些最佳實踐/指南?

關於我

獲取更多技術相關文章,關注公衆號」前端女塾「。

回覆加羣,便可加入」前端仙女羣「

您也能夠掃描添加下方的微信並備註 Sol 加前端交流羣,交流學習。

相關文章
相關標籤/搜索