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 better React code

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

Share

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

This article mainly introduces "how to write better React code". In daily operation, I believe many people have doubts about how to write better React code. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "how to write better React code". Next, please follow the editor to study!

1. Deconstructing props

Deconstructing objects (especially props) in JS can greatly reduce repetition in your code. Look at the following example:

/ / Parent Component import React from 'react'; import CoffeeCard from'. / CoffeeCard' Const CafeMenu = () = > {const coffeeList = [{id: '0percent, name:' Espresso', price: '2.00percent, size:' 16'}, {id: '1percent, name:' Cappuccino', price: '3.50' Size: '24'}, {id:' 2percent, name: 'Caffee Latte', price:' 2.70percent, size: '12'}] Return coffeeList.map (item = > ());}; export default CafeMenu

The CafeMenu component is used to store the list of available drinks, and now we want to create another component that can display one drink. Without deconstructing props, our code would look like this:

/ / Child Component import React from 'react'; const CoffeeCard = props = > {return ({props.coffee.name})

Price: {props.coffee.price} $

Size: {props.coffee.size} oz

);}; export default CoffeeCard

As you can see, it doesn't look good. Every time we need to get a property, we repeat props.coffee. Fortunately, we can simplify it by deconstructing it.

/ / Child Component (after destructuring props) import React from 'react'; const CoffeeCard = props = > {const {name, price, size} = props.coffee; return ({name})

Price: {price} $

Size: {size} oz

);}; export default CoffeeCard

If we want to pass a large number of parameters to the subcomponents, we can also deconstruct the props directly in the constructor (or the parameters of the function component). For example:

/ / Parent Component import React from 'react'; import ContactInfo from'. / ContactInfo'; const UserProfile = () = > {const name = 'John Locke'; const email =' john@locke.com'; const phone = '01632 960668; return;}; export default UserProfile; / / Child Component import React from' react'; const ContactInfo = ({name, email, phone}) = > {return ({name})

E-mail: {email}

Phone: {phone}

);}; export default ContactInfo

two。 Maintain the order of importing modules

Sometimes (especially in "container components"), we need to use many different modules, and component import looks a bit confusing, such as:

Import {Auth} from 'aws-amplify'; import React from' react'; import SidebarNavigation from'. / components/SidebarNavigation'; import {EuiPage, EuiPageBody} from'@ elastic/eui'; import {keyCodes} from'@ elastic/eui/lib/services'; import'. / index.css' import HeaderNavigation from'. / components/HeaderNavigation'; import Routes from'. / Routes'

There are many different views on the ideal order of import modules. I suggest you refer to it and find the one that suits you.

As for myself, I usually group imports by type and sort them alphabetically (this is optional). I also tend to keep the following order:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Standard module

Third-party module

Import your own code (component)

Module-specific imports (such as CSS,PNG, etc.)

Code for testing only

With a quick refactoring, our module import looks much more comfortable.

Import React from 'react'; import {Auth} from' aws-amplify'; import {EuiPage, EuiPageBody} from'@ elastic/eui'; import {keyCodes} from'@ elastic/eui/lib/services'; import HeaderNavigation from'. / components/HeaderNavigation'; import SidebarNavigation from'. / components/SidebarNavigation'; import Routes from'. / Routes'; import'. / index.css'

3. Use Fragments

In our components, we often return multiple elements. A React component cannot return multiple child nodes, so we usually wrap them in div. Sometimes there is a problem with such a solution. For example, in this example:

We are going to create a Table component that contains a Columns component.

Import React from 'react'; import Columns from'. / Columns'; const Table = () = > {return ();}; export default Table

The Columns component contains some td elements. Since we cannot return multiple child nodes, we need to wrap these elements in div.

Import React from 'react'; const Columns = () = > {return (Hello World);}; export default Columns

Then an error was reported because div cannot be placed in the tr tag. We can use the Fragment tag to solve this problem, as follows:

Import React, {Fragment} from 'react'; const Columns = () = > {return (Hello World);}; export default Columns

We can think of a Fragment as an invisible div. It wraps the element in a tag in the child component, takes it to the parent component, and disappears.

You can also use shorter syntax, but it does not support key and attributes.

Import React from 'react'; const Columns = () = > {return (Hello World);}; export default Columns

4. Using presentation components and container components

The components of the application are divided into display (puppet) components and container (smart) components. If you don't know what these are, you can introduce them as follows:

Display component

The main focus is on UI, which is responsible for the appearance of components.

The data is provided by props, and API should not be called in puppet components, which is the work of intelligent components.

Apart from UI's dependency packages, they do not need to rely on the application

They may include state, but they are only used to manipulate the UI itself-they should not store application data.

Puppet components are: load indicator, mode, button, input.

Container component

They do not care about styles and usually do not contain any styles.

They are used to process data, request data, capture changes, and pass application data

Responsible for managing state, re-rendering components, etc.

It may depend on applications, calling Redux, lifecycle methods, API, libraries, and so on.

Benefits of using presentation components and container components

Better readability

Better reusability

Easier to test

In addition, it conforms to the "single responsibility principle"-one component is responsible for the appearance and the other is responsible for the data.

Example

Let's look at a simple example. This is a BookList component that takes book data from API and displays it in a list.

Import React, {useState, useEffect} from 'react'; const BookList = () = > {const [books, setBooks] = useState ([]); const [isLoading, setLoading] = useState (false); useEffect () = > {setLoading (true); fetch (' api/books') .then (res = > res.json ()) .then (books = > {setBooks (books)) SetLoading (false);});}, []); const renderLoading = () = > {return

Loading...

;}; const renderBooks = () = > {return ({books.map (book = > ({book.name}))});}; return {isLoading? RenderLoading (): renderBooks ()};}; export default BookList

The problem with this component is that it is responsible for too many things. It gets and presents the data. It is also associated with a specific interface, so you cannot use this component to display a list of books for a specific user without copying the code.

Now, let's try to divide this component into a presentation component and a container component.

Import React from 'react'; const BookList = ({books, isLoading}) = > {const renderLoading = () = > {return

Loading...

;}; const renderBooks = () = > {return ({books.map (book = > ({book.name}))});}; return {isLoading? RenderLoading (): renderBooks ()};}; export default BookList; import React, {useState, useEffect} from 'react'; import BookList from'. / BookList'; const BookListContainer = () = > {const [books, setBooks] = useState ([]); const [isLoading, setLoading] = useState (false); useEffect () = > {setLoading (true) Fetch ('/ api/books') .then (res = > res.json ()) .then (books = > {setBooks (books); setLoading (false);});}, []); return;}; export default BookListContainer

5. Use styled-components

Styling React components has always been a challenge. Finding misspelled class names, maintaining large CSS files, and dealing with compatibility issues can sometimes be painful.

Styled-components is a common css in js class library. Like all similar class libraries, js enables it to solve the capabilities that native css does not have, such as variables, loops, functions, and so on.

To start using styled-components, you need to first install dependencies:

Npm i styled-components

Here is an example:

Import React from 'react'; import styled from' styled-components'; const Grid = styled.div` display: flex; `; const Col = styled.div` display: flex; flex-direction: column;`; const MySCButton = styled.divon` background: ${props = > (props.primary? Props.mainColor: 'white')}; color: ${props = > (props.primary? 'white': props.mainColor)}; display: block; font-size: 1em; margin: 1em; padding: 0.5em 1em; border: 2px solid ${props = > props.mainColor}; border-radius: 15px; ` Function App () {return (My 1st Button My 2st Button My 3st Button My 4st Button My 5st Button My 6st Button);} export default App

This is just a simple example of how stylized components work, but they can do much more than that. You can learn more about styling components in its official documentation.

At this point, the study on "how to write better React code" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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