In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to write a beautiful React component, for this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.
In the product development of Walmart Labs, we have done a lot of Code Review work, which ensures that I have the opportunity to learn their code style and style from the code of many good engineers. In this blog post, I will share my five favorite component patterns and code chips. But first I want to talk about why we need to focus on improving the reading experience of the code. It's as if you have many ways to dress up a cat, if you dress up your cat like this:
You may think that turnips and vegetables have their own preferences, but the code itself should be guaranteed to be readable, especially in a team where your code is destined to be read by others. Computers don't care, no matter what you throw at them, they will honestly explain, but your teammates won't, they will throw ugly code back in your face. The so-called Pretty Components should include the following features:
It is easy to understand even without any comments
Better performance than cluttered code
Easier to do Bug traceability
Concise and clear, ten thousand sentences at a time
SFC:Stateless Functional Component
I think one pattern that we often overlook in development is the so-called Stateless Functional Component, but this is my personal React component optimization pattern, not one of them. I like these patterns not only because they reduce a lot of template code, but also because they can effectively improve the performance of components. All in all, SFC can make your app run faster and grow more handsome.
Intuitively, SFC refers to components that have only one rendering function, but this simple change can avoid a lot of meaningless detection and memory allocation. Let's take a look at a practical example to see the specific role of SFC, such as:
If we use the orthodox way of writing React components, we can get the following code:
Export default class RelatedSearch extends React.Component {constructor (props) {super (props); this._handleClick = this._handleClick.bind (this);} _ handleClick (suggestedUrl, event) {event.preventDefault (); this.props.onClick (suggestedUrl) } render () {return (Related Searches: {this.props.relatedQueries.map ((query, index) = > this._handleClick (query.searchQuery) Event)} key= {index} > {query.searchText})}) }}
Using SFC mode, you can save about 29% of the code:
Const _ handleClick (suggestedUrl, onClick, event) = > {event.preventDefault (); onClick (suggestedUrl);} Const RelatedSearch = ({relatedQueries, onClick}) = > Related Searches: {relatedQueries.map ((query, index) = > _ handleClick (query.searchQuery, onClick, event)} key= {index} > {query.searchText})} export default RelatedSearch
The reduction in the amount of code comes from two main sources:
No constructor (5 lines)
Replace the Render statement with Arrow Function (4 lines)
In fact, the most fascinating thing about SFC is not only the reduction in the amount of code, but also the improvement in readability. The SFC pattern itself is a practical paradigm of the so-called pure components, and removing the constructor and extracting the click event callback function _ handleClick () out of the component can make the JSX code more pure. Another nice thing is that SFC defines the input Props variable in the form of Arrow Function, that is, the Props that the component depends on is declared in Object Destructring syntax:
Const RelatedSearch = ({relatedQueries, onClick}) = >
This not only makes the Props of the component clearer, but also avoids redundant this.props expressions, thus making the code more readable.
I also want to emphasize that although I admire SFC, I can't abuse it. The best place to use SFC is where you used pure components before. In Walmart Labs, we use Redux to manage the state of the application, which means that most of our components are pure components, which gives SFC a broad application space. Generally speaking, components with the following characteristics are absolutely not suitable for using SFC:
Need to customize the lifecycle management of the entire component
Need to use refs
Conditional Components
JSX itself does not support if expressions, but we can use logical expressions to avoid splitting the code into different submodules, something like this:
Render () {{this.props.isGrid?:}}
This expression is very effective when you choose one of the two to render, but it is not friendly to selectively render one, such as the following:
Render () {{this.props.isSoftSort?: null}}
It does work, but it looks weird. We can do this in a more semantic and friendly way, using logic and expressions and then returning components:
Render () {{!! this.props.isSoftSort & &}}
However, this point is also a matter of opinion, and everyone can do as they like.
Arrow Syntax In React And Redux
ES2015 contains a lot of delicious grammatical candy, I * is that Arrow Notation. This feature is useful when writing components:
Const SoftSort = ({hardSortUrl, sortByName, onClick}) = > {return (Showing results sorted by both Relevance and {sortByName}. OnClick (ev, hardSortUrl)} > Sort results by {sortByName} only;}
The function of this function is to return the JSX object, or we can ignore the return statement:
Const SoftSort = ({hardSortUrl, sortByName, onClick}) = > Showing results sorted by both Relevance and {sortByName}. OnClick (ev, hardSortUrl)} > Sort results by {sortByName} only
There are a lot less lines of code!
Another area that I think is very suitable for Arrow Function is Redux's mapStateToProps function:
Const mapStateToProps = ({isLoading}) > {return ({loading: isLoading,});}
Note that if you return Object, you need to wrap it in curly braces:
Const mapStateToProps = ({isLoading}) = > ({loading: isLoading})
The core point of using Arrow Function optimization is that it can improve the overall readability of the code by focusing on important parts of the function and avoid the noise caused by too much template code.
Rational use of Object Destructing and Spread Attributes
Large components are often trapped by the dilemma of too long this.props, typically as follows:
Render () {return ();}
So many Props probably seem to have a headache. If we were to transfer these Props to the next layer, it would probably look like this:
Render () {const {hidePriceFulfillmentDisplay, primaryOffer, productType, productPageUrl, inventory, submapType, ppu, isLoggedIn, gridView} = this.props; return ();}
Regardless of unKnown Props for the time being, we can use deconstruction assignment to achieve this function:
Render () {const props = this.props; return}
Method Definition Shorthand
This method may not be very useful, but it can still make your code more beautiful. If you want to add functions to Object, you can use ES2015 Method Definition Shorthand instead of traditional ES5 expressions, such as:
If you want to set a default null method, you can also use this method:
ProductRating.defaultProps = {onStarsClick () {}}; the answer to the question on how to write beautiful React components is shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.