<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          編寫(xiě)簡(jiǎn)潔的React代碼建議

          共 8532字,需瀏覽 18分鐘

           ·

          2021-04-26 17:47

          前言

          干凈的代碼易于閱讀,簡(jiǎn)單易懂,而且組織整齊。在這篇文章中,列舉了一些平時(shí)可能需要關(guān)注的點(diǎn)。

          如果你不同意其中任何一條,那也完全沒(méi)問(wèn)題。


          只對(duì)一個(gè)條件進(jìn)行條件性渲染

          如果你需要在一個(gè)條件為真時(shí)有條件地呈現(xiàn)一些東西,在一個(gè)條件為假時(shí)不呈現(xiàn)任何東西,不要使用三元運(yùn)算符。使用&&運(yùn)算符代替。

          糟糕的例子:

          import React, { useState } from 'react'

          export const ConditionalRenderingWhenTrueBad = () => {
          const [showConditionalText, setShowConditionalText] = useState(false)

          const handleClick = () =>
          setShowConditionalText(showConditionalText => !showConditionalText)

          return (
          <div>
          <button onClick={handleClick}>Toggle the text</button>
          {showConditionalText ? <p>The condition must be true!</p> : null}
          </div>
          )
          }

          好的例子:

          import React, { useState } from 'react'

          export const ConditionalRenderingWhenTrueGood = () => {
          const [showConditionalText, setShowConditionalText] = useState(false)

          const handleClick = () =>
          setShowConditionalText(showConditionalText => !showConditionalText)

          return (
          <div>
          <button onClick={handleClick}>Toggle the text</button>
          {showConditionalText && <p>The condition must be true!</p>}
          </div>
          )
          }

          有條件的渲染是指在任何條件下

          如果你需要在一個(gè)條件為真時(shí)有條件地呈現(xiàn)一個(gè)東西,在條件為假時(shí)呈現(xiàn)另一個(gè)東西,請(qǐng)使用三元運(yùn)算符。

          糟糕的例子:

          import React, { useState } from 'react'

          export const ConditionalRenderingBad = () => {
          const [showConditionOneText, setShowConditionOneText] = useState(false)

          const handleClick = () =>
          setShowConditionOneText(showConditionOneText => !showConditionOneText)

          return (
          <div>
          <button onClick={handleClick}>Toggle the text</button>
          {showConditionOneText && <p>The condition must be true!</p>}
          {!showConditionOneText && <p>The condition must be false!</p>}
          </div>
          )
          }

          好的例子:

          import React, { useState } from 'react'

          export const ConditionalRenderingGood = () => {
          const [showConditionOneText, setShowConditionOneText] = useState(false)

          const handleClick = () =>
          setShowConditionOneText(showConditionOneText => !showConditionOneText)

          return (
          <div>
          <button onClick={handleClick}>Toggle the text</button>
          {showConditionOneText ? (
          <p>The condition must be true!</p>
          ) : (
          <p>The condition must be false!</p>
          )}
          </div>
          )
          }

          Boolean props

          一個(gè)真實(shí)的props可以提供給一個(gè)組件,只有props名稱(chēng)而沒(méi)有值,比如:myTruthyProp。寫(xiě)成myTruthyProp={true}是不必要的。

          糟糕的例子:

          import React from 'react'

          const HungryMessage = ({ isHungry }) => (
          <span>{isHungry ? 'I am hungry' : 'I am full'}</span>
          )

          export const BooleanPropBad = () => (
          <div>
          <span>
          <b>This person is hungry: </b>
          </span>
          <HungryMessage isHungry={true} />
          <br />
          <span>
          <b>This person is full: </b>
          </span>
          <HungryMessage isHungry={false} />
          </div>
          )

          好的例子:

          import React from 'react'

          const HungryMessage = ({ isHungry }) => (
          <span>{isHungry ? 'I am hungry' : 'I am full'}</span>
          )

          export const BooleanPropGood = () => (
          <div>
          <span>
          <b>This person is hungry: </b>
          </span>
          <HungryMessage isHungry />
          <br />
          <span>
          <b>This person is full: </b>
          </span>
          <HungryMessage isHungry={false} />
          </div>
          )

          String props

          可以用雙引號(hào)提供一個(gè)字符串道具值,而不使用大括號(hào)或反斜線。

          糟糕的例子:

          import React from 'react'

          const Greeting = ({ personName }) => <p>Hi, {personName}!</p>

          export const StringPropValuesBad = () => (
          <div>
          <Greeting personName={"John"} />
          <Greeting personName={'Matt'} />
          <Greeting personName={`Paul`} />
          </div>
          )

          好的例子:

          import React from 'react'

          const Greeting = ({ personName }) => <p>Hi, {personName}!</p>

          export const StringPropValuesGood = () => (
          <div>
          <Greeting personName="John" />
          <Greeting personName="Matt" />
          <Greeting personName="Paul" />
          </div>
          )

          事件處理函數(shù)

          如果一個(gè)事件處理程序只需要事件對(duì)象的一個(gè)參數(shù),你就可以像這樣提供函數(shù)作為事件處理程序:onChange={handleChange}。

          你不需要像這樣把函數(shù)包在一個(gè)匿名函數(shù)中。

          糟糕的例子:

          import React, { useState } from 'react'

          export const UnnecessaryAnonymousFunctionsBad = () => {
          const [inputValue, setInputValue] = useState('')

          const handleChange = e => {
          setInputValue(e.target.value)
          }

          return (
          <>
          <label htmlFor="name">Name: </label>
          <input id="name" value={inputValue} onChange={e => handleChange(e)} />
          </>
          )
          }

          好的例子:

          import React, { useState } from 'react'

          export const UnnecessaryAnonymousFunctionsGood = () => {
          const [inputValue, setInputValue] = useState('')

          const handleChange = e => {
          setInputValue(e.target.value)
          }

          return (
          <>
          <label htmlFor="name">Name: </label>
          <input id="name" value={inputValue} onChange={handleChange} />
          </>
          )
          }

          將組件作為props傳遞

          當(dāng)把一個(gè)組件作為props傳遞給另一個(gè)組件時(shí),如果該組件不接受任何props,你就不需要把這個(gè)傳遞的組件包裹在一個(gè)函數(shù)中。

          糟糕的例子:

          import React from 'react'

          const CircleIcon = () => (
          <svg height="100" width="100">
          <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
          </svg>
          )

          const ComponentThatAcceptsAnIcon = ({ IconComponent }) => (
          <div>
          <p>Below is the icon component prop I was given:</p>
          <IconComponent />
          </div>
          )

          export const UnnecessaryAnonymousFunctionComponentsBad = () => (
          <ComponentThatAcceptsAnIcon IconComponent={() => <CircleIcon />} />
          )

          好的例子:

          import React from 'react'

          const CircleIcon = () => (
          <svg height="100" width="100">
          <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
          </svg>
          )

          const ComponentThatAcceptsAnIcon = ({ IconComponent }) => (
          <div>
          <p>Below is the icon component prop I was given:</p>
          <IconComponent />
          </div>
          )

          export const UnnecessaryAnonymousFunctionComponentsGood = () => (
          <ComponentThatAcceptsAnIcon IconComponent={CircleIcon} />
          )

          為定義的props

          未定義的props被排除在外,所以如果props未定義是可以的,就不要擔(dān)心提供未定義的回退。

          糟糕的例子:

          import React from 'react'

          const ButtonOne = ({ handleClick }) => (
          <button onClick={handleClick || undefined}>Click me</button>
          )

          const ButtonTwo = ({ handleClick }) => {
          const noop = () => {}

          return <button onClick={handleClick || noop}>Click me</button>
          }

          export const UndefinedPropsBad = () => (
          <div>
          <ButtonOne />
          <ButtonOne handleClick={() => alert('Clicked!')} />
          <ButtonTwo />
          <ButtonTwo handleClick={() => alert('Clicked!')} />
          </div>
          )

          好的例子:

          import React from 'react'

          const ButtonOne = ({ handleClick }) => (
          <button onClick={handleClick}>Click me</button>
          )

          export const UndefinedPropsGood = () => (
          <div>
          <ButtonOne />
          <ButtonOne handleClick={() => alert('Clicked!')} />
          </div>
          )

          設(shè)置依賴(lài)前一個(gè)狀態(tài)的狀態(tài)

          如果新的狀態(tài)依賴(lài)于之前的狀態(tài),那么一定要把狀態(tài)設(shè)置為之前狀態(tài)的函數(shù)。React的狀態(tài)更新可以是分批進(jìn)行的,如果不這樣寫(xiě)你的更新就會(huì)導(dǎo)致意外的結(jié)果。

          糟糕的例子:

          import React, { useState } from 'react'

          export const PreviousStateBad = () => {
          const [isDisabled, setIsDisabled] = useState(false)

          const toggleButton = () => setIsDisabled(!isDisabled)

          const toggleButton2Times = () => {
          for (let i = 0; i < 2; i++) {
          toggleButton()
          }
          }

          return (
          <div>
          <button disabled={isDisabled}>
          I'm {isDisabled ? 'disabled' : 'enabled'}
          </button>
          <button onClick={toggleButton}>Toggle button state</button>
          <button onClick={toggleButton2Times}>Toggle button state 2 times</button>
          </div>
          )
          }

          好的例子:

          import React, { useState } from 'react'

          export const PreviousStateGood = () => {
          const [isDisabled, setIsDisabled] = useState(false)

          const toggleButton = () => setIsDisabled(isDisabled => !isDisabled)

          const toggleButton2Times = () => {
          for (let i = 0; i < 2; i++) {
          toggleButton()
          }
          }

          return (
          <div>
          <button disabled={isDisabled}>
          I'm {isDisabled ? 'disabled' : 'enabled'}
          </button>
          <button onClick={toggleButton}>Toggle button state</button>
          <button onClick={toggleButton2Times}>Toggle button state 2 times</button>
          </div>
          )
          }

          總結(jié)

          以下做法并非針對(duì)React,而是在JavaScript(以及任何編程語(yǔ)言)中編寫(xiě)干凈代碼的良好做法。

          稍微做個(gè)總結(jié):

          • 將復(fù)雜的邏輯提取為明確命名的函數(shù)
          • 將神奇的數(shù)字提取為常量
          • 使用明確命名的變量

          我是TianTian,我們下一期見(jiàn)!!!

          END



          如果覺(jué)得這篇文章還不錯(cuò)
          點(diǎn)擊下面卡片關(guān)注我,交個(gè)朋友
          來(lái)個(gè)【分享、點(diǎn)贊、在看】三連支持一下吧

             “分享、點(diǎn)贊在看” 支持一波 

          瀏覽 41
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  日本高清 精品 | 男人AV天堂电影 | 成 年 人 黄 色 视频 网站 久久久 | 四虎乱伦视频 | 黄色伊人网|