当前位置: 首页 > 科技观察

你应该学习的React开发技巧

时间:2023-03-14 19:56:26 科技观察

干净的代码不仅仅是工作代码。干净的代码易于阅读、理解和组织。在本文中,我们将探讨六种编写更干净的React代码的方法。在阅读这些建议时,记住它们是什么很重要:相信这些实践将帮助我们编写自己的React代码。让我们一起学习吧!1.只为一个条件渲染如果你想在某个条件为真时渲染某些元素,请不要使用三元运算符。请改用&&运算符。不推荐:importReact,{useState}from'react'exportconstConditionalRenderingWhenTrueBad=()=>{const[showConditionalText,setShowConditionalText]=useState(false)consthandleClick=()=>setShowConditionalText(showConditionalText=>!showConditionalText)return(

切换文字{showConditionalText?

设置显示内容

:null}
)}推荐写法:importReact,{useState}from'react'exportconstConditionalRenderingWhenTrueGood=()=>{const[showConditionalText,setShowConditionalText]=useState(false)consthandleClick=()=>setShowConditionalText(showConditionalText=>!showConditionalText)return(
切换文本{showConditionalText&&

设置显示内容!

}
)}2.BooleanProps缩写isHungry缩写不推荐:importReactfrom'react'constHungryMessage=({isHungry})=>({isHungry?'Iamhungry':'Iamfull'})exportconstBooleanPropBad=()=>(
)推荐写法:importReactfrom'react'constHungryMessage=({isHungry})=>({isHungry?'Iamhungry':'Iamfull'})exportconstBooleanPropGood=()=>(
)3.StringPropsabbreviatedpersonName缩写不推荐:importReactfrom'react'constGreeting=({personName})=>

嗨,{personName}!

exportconstStringPropValuesBad=()=>(
)推荐写法:importReactfrom'react'constGreeting=({personName})=>

嗨,{personName}!

exportconstStringPropValuesGood=()=>(
)4.事件处理程序简写onC汉格简写,不推荐:importReact,{useState}from'react'exportconstUnnecessaryAnonymousFunctionsBad=()=>{const[inputValue,setInputValue]=useState('')constandleChange=e=>{setInputValue(e.target.value)}return(<Name:handleChange(e)}/>>)}推荐写法:importReact,{useState}from'react'exportconstUnnecessaryAnonymousFunctionsGood=()=>{const[inputValue,setInputValue]=useState('')constandleChange=e=>{setInputValue(e.target.value)}return(<>Name:>)}5.作为参数返回给IconComponent的组件是缩写的,不推荐:importReactfrom'react'constCircleIcon=()=>()constComponentThatAcceptsAnIcon=({IconComponent})=>(
)exportconstUnnecessaryAnonymousFunctionComponentsBad=()=>(}/>)推荐写法:importReactfrom'react'constCircleIcon=()=>()constComponentThatAcceptsAnIcon=({IconComponent})=>(
)exportconstUnnecessaryAnonymousFunctionComponentsGood=()=>()6.设置依赖于前一个pros的pros如果新状态依赖于前一个state,总是将状态设置为前一个state的函数React状态更新可以批量处理,不这样写更新会导致意想不到的结果。setIsDisabled处的缩写不推荐:importReact,{useState}from'react'exportconstPreviousStateBad=()=>{const[isDisabled,setIsDisabled]=useState(false)consttoggleButton=()=>setIsDisabled(!isDisabled)consttoggleButton2Times=()=>{for(leti=0;i<2;i++){toggleButton()}}return(
我{isDisabled?'disabled':'enabled'}切换按钮状态切换按钮状态2次
)}推荐写法:importReact,{useState}from'react'exportconstPreviousStateGood=()=>{const[isDisabled,setIsDisabled]=useState(false)consttoggleButton=()=>setIsDisabled(isDisabled=>!isDisabled)consttoggleButton2Times=()=>{for(leti=0;i<2;i++){toggleButton()}}return(
我{isDisabled?'disabled':'enabled'}切换按钮状态切换按钮状态2次
)}本文转载自微信公众号“前端达人”,转载文章可通过以下二维码关注,转载请联系前端人们公众号。