React Clean Code - 编写更好、更干净的代码的简单方法

2025-05-28

React Clean Code - 编写更好、更干净的代码的简单方法

整洁的代码不仅仅是能正常工作的代码。整洁的代码易于阅读、易于理解,并且结构清晰。在本文中,我们将探讨编写更简洁的 React 代码的八种方法。

在阅读这些建议时,务必牢记,它们仅仅是建议而已。如果您不同意其中任何一条,完全没问题。不过,这些实践在我自己编写 React 代码时确实很有帮助。让我们开始吧!


1. 仅针对一个条件进行条件渲染

如果您需要在条件为 时有条件地渲染某些内容,true而在条件为 时不渲染任何内容false,请不要使用三元运算符。请改用&&运算符。

不好的例子:

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 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>
)
}
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>
)
}

2. 根据任一条件进行条件渲染

如果您需要在条件为时有条件地渲染一件事物,true并在条件为时渲染另一件事false,请使用三元运算符。

不好的例子:

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 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>
)
}
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>
)
}

3. 布尔属性

可以将一个真值 prop 提供给一个组件,只需要 prop 名称,不需要值,像这样:myTruthyProp。像这样写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 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>
)
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>
)

4. 字符串 props

字符串 prop 值可以用双引号提供,无需使用花括号或反引号。

不好的例子:

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 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>
)
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>
)

5. 事件处理函数

如果事件处理程序仅接受对象的单个参数Event,则您只需提供该函数作为事件处理程序,如下所示:onChange={handleChange}。您不需要将函数包装在匿名函数中,如下所示:onChange={e => handleChange(e)}

不好的例子:

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 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} />
</>
)
}
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} />
</>
)
}

6. 将组件作为 props 传递

当将一个组件作为 prop 传递给另一个组件时,如果该组件不接受任何 props,则无需将传递的组件包装在函数中。

不好的例子:

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 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} />
)
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} />
)

7. 未定义的 props

undefined未定义的道具被排除在外,因此如果道具未定义,则不必担心提供后备。

不好的例子:

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 || 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>
)
import React from 'react'
const ButtonOne = ({ handleClick }) => (
<button onClick={handleClick}>Click me</button>
)
export const UndefinedPropsGood = () => (
<div>
<ButtonOne />
<ButtonOne handleClick={() => alert('Clicked!')} />
</div>
)

8. 设置依赖于先前状态的状态

如果新状态依赖于先前状态,则始终将状态设置为先前状态的函数。React 状态更新可以批量处理,如果不以这种方式编写更新,可能会导致意外的结果。

不好的例子:

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 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>
)
}
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>
)
}

荣誉奖

以下实践并非特定于 React,而是使用 JavaScript(以及任何编程语言)编写干净代码的良好实践。

  • 将复杂的逻辑提取到名称明确的函数中
  • 将魔法数字提取为常量
  • 使用明确命名的变量

编码愉快!

文章来源:https://dev.to/thawkin3/react-clean-code-simple-ways-to-write-better-and-cleaner-code-2loa
PREV
软件工程是一场失败者的游戏
NEXT
来自 Tech Lead 的经验教训:角色、职责和建议