Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to write concise React code

2025-01-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces you how to write concise React code, the content is very detailed, interested friends can refer to, hope to be helpful to you.

Conditional rendering of only one condition

If you need to present something conditionally when a condition is true, do not present anything when a condition is false, do not use the ternary operator. Use the & & operator instead.

Bad example: 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!

Good example: 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!

})} conditional rendering means that under any condition

If you need to render one thing conditionally when one condition is true and another when the condition is false, use the ternary operator.

Bad example: 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!

Good example: 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

A real props can be provided to a component with only the props name but no value, such as myTruthyProp. It is unnecessary to write myTruthyProp= {true}.

Bad example: 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:) A good example: 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

You can provide a string prop value in double quotes without using curly braces or backslashes.

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

Hi, {personName}!

Export const StringPropValuesBad = () = > () A good example: import React from 'react' const Greeting = ({personName}) = >

Hi, {personName}!

Export const StringPropValuesGood = () = > () event handler

If an event handler requires only one parameter to the event object, you can provide a function as an event handler like this: onChange= {handleChange}.

You don't need to wrap the function in an anonymous function like this.

Bad example: import React, {useState} from 'react' export const UnnecessaryAnonymousFunctionsBad = () = > {const [inputValue, setInputValue] = useState ('') const handleChange = e = > {setInputValue (e.target.value)} return (Name: handleChange (e)} / >)} good example: import React, {useState} from 'react' export const UnnecessaryAnonymousFunctionsGood = () = > {const [inputValue SetInputValue] = useState ('') const handleChange = e = > {setInputValue (e.target.value)} return (Name:)} pass the component as props

When passing a component as a props to another component, if the component does not accept any props, you do not need to wrap the passed component in a function.

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

Below is the icon component prop I was given:

) export const UnnecessaryAnonymousFunctionComponentsBad = () = > (} / >) A good example: import React from 'react' const CircleIcon = () = > () const ComponentThatAcceptsAnIcon = ({IconComponent}) = > (

Below is the icon component prop I was given:

) export const UnnecessaryAnonymousFunctionComponentsGood = () = > () is the defined props

Undefined props is excluded, so don't worry about providing undefined fallback if props is not defined.

Bad example: import React from 'react' const ButtonOne = ({handleClick}) = > (Click me) const ButtonTwo = ({handleClick}) = > {const noop = () > {} return Click me} export const UndefinedPropsBad = () = > (alert (' handleClick')} / > alert ('handleClick')} / >) good example: import React from 'react' const ButtonOne = ({handleClick}) = > (Click me) export const UndefinedPropsGood = () = > (alert ('Clickedlings')} / >) sets a state that depends on the previous state

If the new state depends on the previous state, be sure to set the state to a function of the previous state. React status updates can be done in batches, and if you don't write your updates in this way, it will lead to unexpected results.

Bad example: 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; iTunes +) {toggleButton ()} return (Isimm {isDisabled? 'disabled':' enabled'} Toggle button state Toggle button state 2 times)} Summary

The following practices are not aimed at React, but are good practices for writing clean code in JavaScript (and any programming language).

Extract complex logic into explicitly named functions

Extract magical numbers into constants

Use explicitly named variables

On how to write concise React code to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report