当前位置:主页 > 查看内容

【译】React代码整洁之道

发布时间:2021-05-06 00:00| 位朋友查看

简介:整洁的代码不仅仅是正常运行的代码,更是要求易于阅读、简单易懂、组织整齐。 在本文中,我们将研究八种代码整洁之道。 在阅读这些建议时,要记住这些只是建议!如果你不同意它们中的任何一个,那也完全没关系。 以下这些实践,个人觉得对我自己编写 React 代……

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

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

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

以下这些实践,个人觉得对我自己编写 React 代码很有帮助。

让我们开始吧!

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

如果需要在条件为 true 时渲染某些内容,而在条件为 false 时不渲染任何内容,不要使 三元表达式,请改用 &&。

🙅‍♂️ 不推荐示例:

  1. import React, { useState } from 'react' 
  2.  
  3. export const ConditionalRenderingWhenTrueBad = () => { 
  4.   const [showConditionalText, setShowConditionalText] = useState(false
  5.  
  6.   const handleClick = () => 
  7.     setShowConditionalText(showConditionalText => !showConditionalText) 
  8.  
  9.   return ( 
  10.     <div> 
  11.       <button onClick={handleClick}>Toggle the text</button> 
  12.       {/* 三元表达式 */} 
  13.       {showConditionalText ? <p>条件为 True!</p> : null}  
  14.     </div> 
  15.   ) 

👍 推荐示例:

  1. import React, { useState } from 'react' 
  2.  
  3. export const ConditionalRenderingWhenTrueGood = () => { 
  4.   const [showConditionalText, setShowConditionalText] = useState(false
  5.  
  6.   const handleClick = () => 
  7.     setShowConditionalText(showConditionalText => !showConditionalText) 
  8.  
  9.   return ( 
  10.     <div> 
  11.       <button onClick={handleClick}>Toggle the text</button> 
  12.       {showConditionalText && <p>条件为 True!</p>} 
  13.     </div> 
  14.   ) 

2. 每一个条件都进行渲染

如果需要在条件为 true 时渲染某些内容,而在条件为 false 时渲染其他内容。使用三元表达式!

🙅‍♂️ 不推荐的示例:

  1. import React, { useState } from 'react' 
  2.  
  3. export const ConditionalRenderingBad = () => { 
  4.   const [showConditionOneText, setShowConditionOneText] = useState(false
  5.  
  6.   const handleClick = () => 
  7.     setShowConditionOneText(showConditionOneText => !showConditionOneText) 
  8.  
  9.   return ( 
  10.     <div> 
  11.       <button onClick={handleClick}>Toggle the text</button> 
  12.       {/* 条件 True 和 False 都要渲染内容 */} 
  13.       {showConditionOneText && <p>条件为 True!</p>} 
  14.       {!showConditionOneText && <p>条件为 Flase!</p>} 
  15.     </div> 
  16.   ) 

👍 推荐示例:

  1. import React, { useState } from 'react' 
  2.  
  3. export const ConditionalRenderingGood = () => { 
  4.   const [showConditionOneText, setShowConditionOneText] = useState(false
  5.  
  6.   const handleClick = () => 
  7.     setShowConditionOneText(showConditionOneText => !showConditionOneText) 
  8.  
  9.   return ( 
  10.     <div> 
  11.       <button onClick={handleClick}>Toggle the text</button> 
  12.       {showConditionOneText ? ( 
  13.         <p>The condition must be true!</p> 
  14.       ) : ( 
  15.         <p>The condition must be false!</p> 
  16.       )} 
  17.     </div> 
  18.   ) 

3. Boolean props

Props 值为 true 的推荐省略不写。

🙅‍♂️ 不推荐示例:

  1. import React from 'react' 
  2.  
  3. const HungryMessage = ({ isHungry }) => ( 
  4.   <span>{isHungry ? 'I am hungry' : 'I am full'}</span> 
  5.  
  6. export const BooleanPropBad = () => ( 
  7.   <div> 
  8.     <span> 
  9.       <b>This person is hungry: </b> 
  10.     </span> 
  11.     <HungryMessage isHungry={true} /> 
  12.     <br /> 
  13.     <span> 
  14.       <b>This person is full: </b> 
  15.     </span> 
  16.     <HungryMessage isHungry={false} /> 
  17.   </div> 

👍 推荐示例:

  1. import React from 'react' 
  2.  
  3. const HungryMessage = ({ isHungry }) => ( 
  4.   <span>{isHungry ? 'I am hungry' : 'I am full'}</span> 
  5.  
  6. export const BooleanPropGood = () => ( 
  7.   <div> 
  8.     <span> 
  9.       <b>This person is hungry: </b> 
  10.     </span> 
  11.     {/* 不需要赋值 true,省略 */} 
  12.     <HungryMessage isHungry /> 
  13.     <br /> 
  14.     <span> 
  15.       <b>This person is full: </b> 
  16.     </span> 
  17.     <HungryMessage isHungry={false} /> 
  18.   </div> 

4. String props

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

🙅‍♂️ 不推荐示例:

  1. import React from 'react' 
  2.  
  3. const Greeting = ({ personName }) => <p>Hi, {personName}!</p> 
  4.  
  5. export const StringPropValuesBad = () => ( 
  6.   <div> 
  7.     <Greeting personName={"John"} /> 
  8.     <Greeting personName={'Matt'} /> 
  9.     <Greeting personName={`Paul`} /> 
  10.   </div> 

👍 推荐示例:

  1. import React from 'react' 
  2.  
  3. const Greeting = ({ personName }) => <p>Hi, {personName}!</p> 
  4.  
  5. export const StringPropValuesGood = () => ( 
  6.   <div> 
  7.     <Greeting personName="John" /> 
  8.     <Greeting personName="Matt" /> 
  9.     <Greeting personName="Paul" /> 
  10.   </div> 

5. Event handler functions

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

🙅‍♂️ 不推荐示例:

  1. import React, { useState } from 'react' 
  2.  
  3. export const UnnecessaryAnonymousFunctionsBad = () => { 
  4.   const [inputValue, setInputValue] = useState(''
  5.  
  6.   const handleChange = e => { 
  7.     setInputValue(e.target.value) 
  8.   } 
  9.  
  10.   return ( 
  11.     <> 
  12.       <label htmlFor="name">Name: </label> 
  13.       {/* 事件只有一个参数,不需要匿名函数*/} 
  14.       <input id="name" value={inputValue} onChange={e => handleChange(e)} /> 
  15.     </> 
  16.   ) 

👍 推荐示例:

  1. import React, { useState } from 'react' 
  2.  
  3. export const UnnecessaryAnonymousFunctionsGood = () => { 
  4.   const [inputValue, setInputValue] = useState(''
  5.  
  6.   const handleChange = e => { 
  7.     setInputValue(e.target.value) 
  8.   } 
  9.  
  10.   return ( 
  11.     <> 
  12.       <label htmlFor="name">Name: </label> 
  13.       <input id="name" value={inputValue} onChange={handleChange} /> 
  14.     </> 
  15.   ) 

6. components as props

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

🙅‍♂️ 不推荐示例:

  1. import React from 'react' 
  2.  
  3. const CircleIcon = () => ( 
  4.   <svg height="100" width="100"
  5.     <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /> 
  6.   </svg> 
  7.  
  8. const ComponentThatAcceptsAnIcon = ({ IconComponent }) => ( 
  9.   <div> 
  10.     <p>Below is the icon component prop I was given:</p> 
  11.     <IconComponent /> 
  12.   </div> 
  13.  
  14. export const UnnecessaryAnonymousFunctionComponentsBad = () => ( 
  15.   {/* 组件不需要包装在函数中 */} 
  16.   <ComponentThatAcceptsAnIcon IconComponent={() => <CircleIcon />} /> 

👍 推荐示例:

  1. import React from 'react' 
  2.  
  3. const CircleIcon = () => ( 
  4.   <svg height="100" width="100"
  5.     <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /> 
  6.   </svg> 
  7.  
  8. const ComponentThatAcceptsAnIcon = ({ IconComponent }) => ( 
  9.   <div> 
  10.     <p>Below is the icon component prop I was given:</p> 
  11.     <IconComponent /> 
  12.   </div> 
  13.  
  14. export const UnnecessaryAnonymousFunctionComponentsGood = () => ( 
  15.   <ComponentThatAcceptsAnIcon IconComponent={CircleIcon} /> 

7. undefined props

如果参数为 undefined 是允许的,那么不要提供 undefined 作为回退值。

🙅‍♂️ 不推荐示例:

  1. import React from 'react' 
  2.  
  3. const ButtonOne = ({ handleClick }) => ( 
  4.   <button onClick={handleClick || undefined}>Click me</button> 
  5.  
  6. const ButtonTwo = ({ handleClick }) => { 
  7.   const noop = () => {} 
  8.  
  9.   return <button onClick={handleClick || noop}>Click me</button> 
  10.  
  11. export const UndefinedPropsBad = () => ( 
  12.   <div> 
  13.     <ButtonOne /> 
  14.     <ButtonOne handleClick={() => alert('Clicked!')} /> 
  15.     <ButtonTwo /> 
  16.     <ButtonTwo handleClick={() => alert('Clicked!')} /> 
  17.   </div> 

👍 推荐示例:

  1. import React from 'react' 
  2.  
  3. const ButtonOne = ({ handleClick }) => ( 
  4.   <button onClick={handleClick}>Click me</button> 
  5.  
  6. export const UndefinedPropsGood = () => ( 
  7.   <div> 
  8.     <ButtonOne /> 
  9.     <ButtonOne handleClick={() => alert('Clicked!')} /> 
  10.   </div> 

8. 设置 state 依赖先前的 state

如果新 state 依赖于先前 state,则始终将 state 设置为先前 state 的函数。可以批处理 React 状态更新。

🙅‍♂️ 不推荐示例:

  1. import React, { useState } from 'react' 
  2.  
  3. export const PreviousStateBad = () => { 
  4.   const [isDisabled, setIsDisabled] = useState(false
  5.  
  6.   const toggleButton = () => setIsDisabled(!isDisabled) 
  7.  
  8.   const toggleButton2Times = () => { 
  9.     for (let i = 0; i < 2; i++) { 
  10.       toggleButton() 
  11.     } 
  12.   } 
  13.  
  14.   return ( 
  15.     <div> 
  16.       <button disabled={isDisabled}> 
  17.         I'm {isDisabled ? 'disabled' : 'enabled'} 
  18.       </button> 
  19.       <button onClick={toggleButton}>Toggle button state</button> 
  20.       <button onClick={toggleButton2Times}>Toggle button state 2 times</button> 
  21.     </div> 
  22.   ) 

👍 推荐示例:

  1. import React, { useState } from 'react' 
  2.  
  3. export const PreviousStateGood = () => { 
  4.   const [isDisabled, setIsDisabled] = useState(false
  5.  
  6.   {/* 推荐设置为函数 */} 
  7.   const toggleButton = () => setIsDisabled(isDisabled => !isDisabled) 
  8.  
  9.   const toggleButton2Times = () => { 
  10.     for (let i = 0; i < 2; i++) { 
  11.       toggleButton() 
  12.     } 
  13.   } 
  14.  
  15.   return ( 
  16.     <div> 
  17.       <button disabled={isDisabled}> 
  18.         I'm {isDisabled ? 'disabled' : 'enabled'} 
  19.       </button> 
  20.       <button onClick={toggleButton}>Toggle button state</button> 
  21.       <button onClick={toggleButton2Times}>Toggle button state 2 times</button> 
  22.     </div> 
  23.   ) 

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

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

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

翻译/润色:ViktorHub


本文转载自网络,原文链接:https://mp.weixin.qq.com/s/jO0g8HJX2XGHhZANJfsM4A
本站部分内容转载于网络,版权归原作者所有,转载之目的在于传播更多优秀技术内容,如有侵权请联系QQ/微信:153890879删除,谢谢!

推荐图文

  • 周排行
  • 月排行
  • 总排行

随机推荐