如何编写简洁的React代码-成都快上网建站

如何编写简洁的React代码

这篇文章给大家介绍如何编写简洁的React代码,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

成都地区优秀IDC服务器托管提供商(成都创新互联公司).为客户提供专业的服务器托管,四川各地服务器托管,服务器托管、多线服务器托管.托管咨询专线:18982081108

如何编写简洁的React代码

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

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

糟糕的例子:

import React, { useState } from 'react'  export const ConditionalRenderingWhenTrueBad = () => {   const [showConditionalText, setShowConditionalText] = useState(false)    const handleClick = () =>     setShowConditionalText(showConditionalText => !showConditionalText)    return (     
       Toggle the text       {showConditionalText ? 

The condition must be true!

 : null}     
   ) }

 好的例子:

import React, { useState } from 'react'  export const ConditionalRenderingWhenTrueGood = () => {   const [showConditionalText, setShowConditionalText] = useState(false)    const handleClick = () =>     setShowConditionalText(showConditionalText => !showConditionalText)    return (     
       Toggle the text       {showConditionalText && 

The condition must be true!

}     
   ) }

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

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

糟糕的例子:

import React, { useState } from 'react'  export const ConditionalRenderingBad = () => {   const [showConditionOneText, setShowConditionOneText] = useState(false)    const handleClick = () =>     setShowConditionOneText(showConditionOneText => !showConditionOneText)    return (     
       Toggle the text       {showConditionOneText && 

The condition must be true!

}       {!showConditionOneText && 

The condition must be false!

}     
   ) }

 好的例子:

import React, { useState } from 'react'  export const ConditionalRenderingGood = () => {   const [showConditionOneText, setShowConditionOneText] = useState(false)    const handleClick = () =>     setShowConditionOneText(showConditionOneText => !showConditionOneText)    return (     
       Toggle the text       {showConditionOneText ? (         

The condition must be true!

       ) : (         

The condition must be false!

       )}     
   ) }

 Boolean props

一个真实的props可以提供给一个组件,只有props名称而没有值,比如:myTruthyProp。写成myTruthyProp={true}是不必要的。

糟糕的例子:

import React from 'react'  const HungryMessage = ({ isHungry }) => (   {isHungry ? 'I am hungry' : 'I am full'} )  export const BooleanPropBad = () => (   
            This person is hungry:                            This person is full:              
 )

 好的例子:

import React from 'react'  const HungryMessage = ({ isHungry }) => (   {isHungry ? 'I am hungry' : 'I am full'} )  export const BooleanPropGood = () => (   
            This person is hungry:                            This person is full:              
 )

 String props

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

糟糕的例子:

import React from 'react'  const Greeting = ({ personName }) => 

Hi, {personName}!

  export const StringPropValuesBad = () => (   
                  
 )

 好的例子:

import React from 'react'  const Greeting = ({ personName }) => 

Hi, {personName}!

  export const StringPropValuesGood = () => (   
                  
 )

 事件处理函数

如果一个事件处理程序只需要事件对象的一个参数,你就可以像这样提供函数作为事件处理程序:onChange={handleChange}。

你不需要像这样把函数包在一个匿名函数中。

糟糕的例子:

import React, { useState } from 'react'  export const UnnecessaryAnonymousFunctionsBad = () => {   const [inputValue, setInputValue] = useState('')    const handleChange = e => {     setInputValue(e.target.value)   }    return (     <>       Name:         handleChange(e)} />        ) }

好的例子:

import React, { useState } from 'react'  export const UnnecessaryAnonymousFunctionsGood = () => {   const [inputValue, setInputValue] = useState('')    const handleChange = e => {     setInputValue(e.target.value)   }    return (     <>       Name:                ) }

将组件作为props传递

当把一个组件作为props传递给另一个组件时,如果该组件不接受任何props,你就不需要把这个传递的组件包裹在一个函数中。

糟糕的例子:

import React from 'react'  const CircleIcon = () => (            )  const ComponentThatAcceptsAnIcon = ({ IconComponent }) => (   
     

Below is the icon component prop I was given:

        
 )  export const UnnecessaryAnonymousFunctionComponentsBad = () => (    } /> )

好的例子:

import React from 'react'  const CircleIcon = () => (            )  const ComponentThatAcceptsAnIcon = ({ IconComponent }) => (   
     

Below is the icon component prop I was given:

        
 )  export const UnnecessaryAnonymousFunctionComponentsGood = () => (    )

为定义的props

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

糟糕的例子:

import React from 'react'  const ButtonOne = ({ handleClick }) => (   Click me )  const ButtonTwo = ({ handleClick }) => {   const noop = () => {}    return Click me }  export const UndefinedPropsBad = () => (   
           alert('Clicked!')} />           alert('Clicked!')} />   
 )

 好的例子:

import React from 'react'  const ButtonOne = ({ handleClick }) => (   Click me )  export const UndefinedPropsGood = () => (   
           alert('Clicked!')} />   
 )

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

如果新的状态依赖于之前的状态,那么一定要把状态设置为之前状态的函数。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 (     
                I'm {isDisabled ? 'disabled' : 'enabled'}              Toggle button state       Toggle button state 2 times     
   ) }

 好的例子:

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 (     
                I'm {isDisabled ? 'disabled' : 'enabled'}              Toggle button state       Toggle button state 2 times     
   ) }

 总结

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

  • 将复杂的逻辑提取为明确命名的函数

  • 将神奇的数字提取为常量

  • 使用明确命名的变量

关于如何编写简洁的React代码就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


分享题目:如何编写简洁的React代码
链接分享:http://kswjz.com/article/gcdogi.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流