【译】React代码整洁之道

开发 前端
整洁的代码不仅仅是正常运行的代码,更是要求易于阅读、简单易懂、组织整齐。在本文中,我们将研究八种代码整洁之道。

[[385736]]

整洁的代码不仅仅是正常运行的代码,更是要求易于阅读、简单易懂、组织整齐。

在本文中,我们将研究八种代码整洁之道。

在阅读这些建议时,要记住这些只是建议!如果你不同意它们中的任何一个,那也完全没关系。

以下这些实践,个人觉得对我自己编写 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>条件为 True!</p> : null}  
    </div> 
  ) 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

 👍 推荐示例:

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>条件为 True!</p>} 
    </div> 
  ) 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

 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> 
      {/* 条件 True 和 False 都要渲染内容 */} 
      {showConditionOneText && <p>条件为 True!</p>} 
      {!showConditionOneText && <p>条件为 Flase!</p>} 
    </div> 
  ) 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

 👍 推荐示例:

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

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

 3. Boolean props

Props 值为 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> 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

 👍 推荐示例:

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> 
    {/* 不需要赋值 true,省略 */} 
    <HungryMessage isHungry /> 
    <br /> 
    <span> 
      <b>This person is full: </b> 
    </span> 
    <HungryMessage isHungry={false} /> 
  </div> 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

 4. String props

Props 值为 String, 使用双引号,不使用花括号或反引号。

🙅‍♂️ 不推荐示例:

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> 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

 👍 推荐示例:

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> 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

 5. Event handler functions

如果一个事件函数只接受一个参数,不需要传入匿名函数:onChange={e=>handleChange(e)},推荐这种写法:onChange={handleChange} 。

🙅‍♂️ 不推荐示例:

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

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.

👍 推荐示例:

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

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

6. components as 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 />} /> 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.

 👍 推荐示例:

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

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

 7. undefined props

如果参数为 undefined 是允许的,那么不要提供 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> 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

 👍 推荐示例:

import React from 'react' 
 
const ButtonOne = ({ handleClick }) => ( 
  <button onClick={handleClick}>Click me</button> 

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

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.

 8. 设置 state 依赖先前的 state

如果新 state 依赖于先前 state,则始终将 state 设置为先前 state 的函数。可以批处理 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> 
  ) 

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.

 👍 推荐示例:

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

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.

 以上就是我推荐的几个写出整洁的 React 代码的实践。

最后,恭喜你读完了本文,欢迎留言交流~

原文地址:https://dev.to/thawkin3/react-clean-code-simple-ways-to-write-better-and-cleaner-code-2loa

翻译/润色:ViktorHub

 

责任编辑:姜华 来源: 前端思维框架
相关推荐

2012-08-01 09:38:17

代码整洁

2012-08-01 09:23:31

代码

2021-01-06 14:42:09

前端Typescript代码

2020-12-09 10:49:33

代码开发GitHub

2020-02-29 16:00:20

代码开发程序员

2012-09-25 09:28:36

程序员代码代码整洁

2011-12-02 10:19:24

CSS

2019-05-14 09:31:16

架构整洁软件编程范式

2021-03-19 07:23:23

Go架构Go工程化

2011-06-03 15:06:30

CSS

2011-06-03 15:21:51

CSS

2022-08-31 12:15:09

JavaScript代码优化

2015-06-17 14:24:48

优秀程序员整洁代码

2025-01-14 00:01:01

2020-03-28 14:57:29

JavaScrip代码函数

2014-12-26 10:06:48

Docker容器代码部署

2010-09-09 13:59:55

CSS

2017-10-24 15:28:27

PHP代码简洁SOLID原则

2018-07-23 08:19:26

编程语言Python工具

2014-03-18 16:12:00

代码整洁编写代码
点赞
收藏

51CTO技术栈公众号