编写简洁的React代码建议

开发 前端
如果你需要在一个条件为真时有条件地呈现一些东西,在一个条件为假时不呈现任何东西,不要使用三元运算符。使用&&运算符代替。

[[395577]]

前言

干净的代码易于阅读,简单易懂,而且组织整齐。在这篇文章中,列举了一些平时可能需要关注的点。

如果你不同意其中任何一条,那也完全没问题。

只对一个条件进行条件性渲染

如果你需要在一个条件为真时有条件地呈现一些东西,在一个条件为假时不呈现任何东西,不要使用三元运算符。使用&&运算符代替。

糟糕的例子:

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

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

 好的例子:

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

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

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

如果你需要在一个条件为真时有条件地呈现一个东西,在条件为假时呈现另一个东西,请使用三元运算符。

糟糕的例子:

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

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

 好的例子:

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.

 Boolean props

一个真实的props可以提供给一个组件,只有props名称而没有值,比如: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> 

  • 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> 
    <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.

 String props

可以用双引号提供一个字符串道具值,而不使用大括号或反斜线。

糟糕的例子:

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.

 事件处理函数

如果一个事件处理程序只需要事件对象的一个参数,你就可以像这样提供函数作为事件处理程序: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.

好的例子:

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.

将组件作为props传递

当把一个组件作为props传递给另一个组件时,如果该组件不接受任何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.

好的例子:

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.

为定义的props

未定义的props被排除在外,所以如果props未定义是可以的,就不要担心提供未定义的回退。

糟糕的例子:

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.

 设置依赖前一个状态的状态

如果新的状态依赖于之前的状态,那么一定要把状态设置为之前状态的函数。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.

 总结

以下做法并非针对React,而是在JavaScript(以及任何编程语言)中编写干净代码的良好做法。

稍微做个总结:

  • 将复杂的逻辑提取为明确命名的函数
  • 将神奇的数字提取为常量
  • 使用明确命名的变量

我是TianTian,我们下一期见!!!

 

责任编辑:姜华 来源: TianTianUp
相关推荐

2022-06-27 06:23:23

代码编程

2022-12-15 10:52:26

代码开发

2024-01-30 08:54:05

JavaScript技巧代码

2023-09-22 12:04:53

Java代码

2012-04-27 16:54:57

Java代码

2011-11-25 10:35:20

Java

2021-06-08 09:35:11

Cleaner ReaReact开发React代码

2020-08-06 16:34:48

Python开发工具

2022-08-28 19:03:18

JavaScript编程语言开发

2016-09-07 19:58:47

CSS代码Web

2017-08-28 14:58:19

CSSFlexbox注释格式优化

2020-10-04 13:15:37

代码技术开发

2022-05-10 10:28:21

JavaScript代码

2024-06-03 11:43:55

2020-09-21 06:58:56

TS 代码建议

2020-05-08 19:52:31

Reactreact.js前端

2017-10-10 16:28:51

前端CSS建议

2024-06-03 11:36:06

Pythonf-string

2017-02-28 21:57:05

React组件

2022-02-25 08:00:00

编程ReactTypescript
点赞
收藏

51CTO技术栈公众号