react 代码编写原则_编写更好的React代码的小技巧

react 代码编写原则

更好的编程 (BETTER PROGRAMMING)

Today we are going to talk about some of my favorite tips, which are super easy to implement or to follow, and that can make your JavaScript code cleaner. Also keep in mind some of the things we are going to learn today apply to JavaScript in general, though the article will focus on React.

今天,我们将讨论我最喜欢的一些技巧,这些技巧非常易于实现或遵循,可以使您JavaScript代码更简洁。 还请记住,尽管本文将重点介绍React,但我们今天将要学习的一些内容通常适用于JavaScript。

对象解构 (Object destructuring)

To get started we will review object destructuring, one of my favorites actually, that can help to keep the code small, clean, and elegant. This topic I love so much that I actually made a whole post about it here:

首先,我们将回顾对象分解,这实际上是我最喜欢的对象之一,它可以帮助保持代码的小巧,简洁和优美。 我非常喜欢这个话题,实际上我在这里写了整篇文章:

Destructuring allows you to break down complex structures into simpler parts. Let’s take a look at an example:

通过解构,您可以将复杂的结构分解为更简单的部分。 让我们看一个例子:

const { title } = props
console.log(title);

A common place where React developers use this technique is with props. Though some people may argue that you lose context when you split the variables, it is usually the case in React, that the context is inherited by the component itself. Let’s take a look at an example to show what I mean.

React开发人员使用此技术的常见地方是props。 尽管有人可能会争辩说,在拆分变量时会丢失上下文,但是在React中通常就是这种情况,即上下文是由组件本身继承的。 让我们看一个例子来说明我的意思。

First, let’s write a simple component to show Task information on the screen:

首先,让我们编写一个简单的组件以在屏幕上显示“任务”信息:

function TaskView(props) {
return (
<h1>{props.task.title}</h1>
<p>{props.task.description}</p>
<span>{props.task.completed ? 'Completed' : 'Pending'}</span>
)
}

It is indeed very simple, however, look at how we repeat props all the time, not very pretty. Let’s look at another way to implement this:

的确确实很简单,但是看看我们如何一直重复道具,不是很漂亮。 让我们看一下另一种实现方法:

function TaskView(props) {
const task = props.task
return (
<h1>{task.title}</h1>
<p>{task.description}</p>
<span>{task.completed ? 'Completed' : 'Pending'}</span>
)
}

It’s a bit better but still, we have tasks everywhere. Now someone who perhaps doesn’t know destructuring may be tempted to do something like:

情况会好一些,但仍然到处都有任务。 现在,也许不知道解构的人可能会被诱惑去做类似的事情:

const title = props.task.title
const description = props.task.description

which adds too much overhead to the declarations. Let’s now see how the component looks like when using destructuring.

这增加了声明的开销。 现在让我们看一下使用解构时组件的外观。

function TaskView(props) {
const { title, description, completed } = props.task
return (
<h1>{title}</h1>
<p>{description}</p>
<span>{completed ? 'Completed' : 'Pending'}</span>
)
}

Now the code is very simple, we keep the JSX very clean from the rest, and we are still in context. It’s perfectly understandable that when we say title we are talking about the Task as is what the component is all about. So keep your names clean, and structure well your components and you will love this feature.

现在的代码非常简单,我们将JSX与其他代码保持一致,并且仍处于上下文中。 完全可以理解的是,当我们说title我们所谈论的是Task以及组件的含义。 因此,请保持您的名字整洁,结构良好,您将喜欢此功能。

简化您的条件语句 (Simplify your conditional statements)

In this section, I want to talk about 3 different scenarios that can help us increase the readability of our code, and it’s so easy, though many times we forget to do it.

在本节中,我想谈谈3种不同的场景,它们可以帮助我们提高代码的可读性,而且很简单,尽管很多时候我们忘记这样做了。

有条件的执行 (Conditional execution)

It is normal that at some point we need to run a statement only if a certain condition happens to be true. Usually, it goes something like:

正常情况下,只有在特定条件为真时,才需要运行语句。 通常,它类似于:

const isFive = (num) => num === 5
if (isFive(5)) {
console.log('It is the number five!')
}

Now, there’s nothing inherently wrong with that code, however, it can be simplified a bit:

现在,该代码没有内在的错误,但是可以将其简化一些:

const isFive = (num) => num === 5
isFive(5) && console.log('It is the number five!')

Nice, but how does it work? JavaScript as many other languages, read conditional statements such us && or || in order from left to right, and they exit at the time they can invalidate the arguments.

很好,但是如何运作? 使用JavaScript和其他许多语言一样,请阅读条件语句,例如&&|| 按从左到右的顺序,并且它们可以使参数无效时退出。

Let’s see an example of this with all conditionals:

让我们来看一个带有所有条件的示例:

const t = 1
t === 1 && t === 2 && t === 3

In that example, JS will first take the first expression t === 1, since that expression is truthy and we have an and conditional, it needs to evaluate the next expression, as we need to guarantee they are all truthy. When it evaluates t === 2, which is falsy, it doesn’t need to evaluate t === 3 at all, it can save that compute as we know the whole statement happens to be false.

在该示例中,JS首先将采用第一个表达式t === 1 ,因为该表达式是真实的,并且我们有and条件,它需要评估下一个表达式,因为我们需要保证它们都是真实的。 当它评估t === 2 ,这是虚假的,它根本不需要评估t === 3 ,由于我们知道整个语句都是false ,因此可以保存该计算。

Amazing! now let’s learn something more about this. It is very common on the internet to see examples of this, however, did you know you can also use the || operator as well?

惊人! 现在让我们了解更多有关此的信息。 在互联网上看到这样的例子是很普遍的,但是,您知道您也可以使用||吗? 运算符也一样?

const isFive = (num) => num === 5
isFive(5) || console.log('It is the number five!') // does not execute the console.log
isFive(10) || console.log('It is not the number five!') // it executes the console.log

Did you notice that what we just did would be equivalent to apply a not to our first example?

您是否注意到我们刚才所做的等同于将not应用于我们的第一个示例?

const isFive = (num) => num === 5
isFive(5) && console.log('It is the number five!') // it executes the console.log
!isFive(10) && console.log('It is not the number five!') // it executes the console.log

三元运算符 (Ternary operator)

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy.

条件(三元)运算符是唯一使用三个操作数JavaScript运算符:条件后跟问号(?),如果条件为真,则执行表达式,后跟冒号(:),最后是表达式如果条件是虚假的,则执行。

This is very commonly used to show different statuses or components to the user depending on a conditional statement. Though I don’t always recommend to use the ternary operator, sometimes a good old fashion if does the job very well. It can be extremely useful for small things.

这通常用于根据条件语句向用户显示不同的状态或组件。 尽管我并不总是建议使用三元运算符,但如果做得很好,有时是一个很好的老方法。 对于小东西,它可能非常有用。

Take a look a the following example:

看下面的例子:

if (completed) {
return 'Completed'
} else {
return 'Pending'
}

Another variation of that, which I still see around is:

我仍然看到的另一种变化是:

if (completed) { return 'Completed'} else { return 'Pending' }

I’m not here to judge, but that can get real messy. Let’s take a look at a way using the ternary operator

我不是来这里判断的,但是那可能会变得很混乱。 让我们看看使用三元运算符的方法

return completed ? 'Completed' : 'Pending'

Much nicer!

好多了!

可选链接 (Optional Chaining)

Last but not least, we have optional chaining (?.) that allows reading the value of a property located deep within a chain of connected objects without having to expressly validate each reference.

最后但并非最不重要的一点是,我们具有可选的链接( ?. ),该链接允许读取位于连接对象链深处的属性的值,而不必明确验证每个引用。

In plain English, it helps to avoid a bunch of if statements just to make sure we have a value on a nested property. Let’s look at an example:

用简单的英语来说,它有助于避免一堆if语句,只是确保我们对嵌套属性有一个值。 让我们看一个例子:

const juan = {
name: 'Juan',
marriedTo: {
name: 'Diana'
}
}console.log(juan.marriedTo.name) // Diana
console.log(juan.divorcedFrom.name) // Cannot read property 'name' of undefined

Ups…. when we tried to access the name of the person we are divorced from, we get an error, because divorcedFrom in our case is undefined. Normally we would solve it like this:

UPS…。 当我们尝试访问与我们离婚的人的姓名时,会收到错误消息,因为在我们的案例中, divorcedFrom是未定义的。 通常我们会这样解决:

if (juan.divorcedFrom) {
console.log(juan.divorcedFrom.name)
}

But that can also get out of hands by adding a lot of ifs just for this purpose. There is a better way using optional chaining.

但这也可以通过添加大量ifs来达到目的。 使用可选链接有更好的方法。

const juan = {
name: 'Juan',
marriedTo: {
name: 'Diana'
}
}console.log(juan.marriedTo?.name) // Diana
console.log(juan.divorcedFrom?.name) // undefined

And this can apply to multiple levels

这可以应用于多个级别

juan.marriedTo?.disvorcedFrom?.kids

Very nice! Let’s move on with the next topic.

非常好! 让我们继续下一个主题。

点差算子 (Spread Operator)

There is no React app without making use of the spread operator, maybe that’s exaggerated, but the spread operator is widely used in react applications, especially when working with reducers, though it is much more than just for that. This is another topic which I covered extensively in the article:

没有使用spread运算符就没有React应用程序,这可能被夸大了,但是spread运算符在react应用程序中被广泛使用,尤其是在使用reducer时,尽管它不仅限于此。 这是我在文章中广泛讨论的另一个主题:

I really recommend that you read it, it’s pretty cool and covers the topic in detail.

我真的建议您阅读它,它非常酷,并且涵盖了详细的主题。

The spread operator allows you to expand an iterable object into a list of its individual elements. Let’s better take a look into some examples:

Spread运算符使您可以将可迭代对象扩展为其单个元素的列表。 让我们更好地看一些例子:

function sum(x, y, z) {
return x + y + z
}const numbers = [1, 2, 3]console.log(sum(...numbers)) // 6

In this case, what we are doing is to transform an array into separate variables that are passed to our sum function. It’s a pretty neat trick. But we can also apply it for objects:

在这种情况下,我们要做的是将array转换为单独的变量,然后将这些变量传递给我们的sum函数。 这是一个很好的技巧。 但是我们也可以将其应用于对象:

const obj1 = { foo: 'bar', x: 42 }
const obj2 = { foo: 'baz', y: 13 }const copyObj1 = { ...obj1 } // This copies all the properties of obj1 into a new object.const merged = { ...obj1, ...obj2 } // This merges all the properties of obj1 and obj2 into a new object.console.log(merged) // {foo: "baz", x: 42, y: 13}

Because we can use this to create new objects or arrays, its ideal to use with Redux, as we can avoid mutating the original objects.

因为我们可以使用它来创建新的对象或数组,所以它非常适合与Redux一起使用,因为我们可以避免对原始对象进行变异。

模板文字 (Template Literals)

Though very popular and beginners friendly, no list would be completed without them. Template literals are basically strings, but not any string, they allow embedded expressions. Let’s take a look.

尽管非常受欢迎并且对初学者很友好,但没有他们就不会完成任何列表。 模板文字基本上是字符串,但不是任何字符串,它们允许嵌入表达式。 让我们来看看。

console.log(`this is a string literal`)

In its more basic form, a string literal is just a string, however, note that for it to be a string literal it must use \`` instead of "or'`. It’s a small detail but makes a huge difference.

字符串文字在其更基本的形式中只是一个字符串,但是请注意,要使其成为字符串文字,必须使用\`` instead ofor '`。这是一个很小的细节,但却有很大的不同。

String literals, for example, support multi-line strings:

例如,字符串文字支持多行字符串:

console.log(`line 1
line 2`)

Or you can also embed expressions

或者您也可以嵌入表达式

const a = 10
const b = 25console.log(`a: ${a} and b: ${b} but more importantly a+b = ${a+b}`) // a: 10 and b: 25 but more importantly a+b = 35

Really cool!

真酷!

结论 (Conclusion)

JavaScript is packed with useful operators, expressions, and tricks to power up our development skills and writer cleaner code. It is also true that some of the things I mention can be personal judgment, but if you look at the React code written on very popular projects you will see they apply these small things all over the place. So they are really good to learn and implement when you write your next React component.

JavaScript包含有用的运算符,表达式和技巧,以增强我们的开发技能和编写更干净的代码。 确实,我提到的某些事情可能是个人判断,但是如果您查看在非常受欢迎的项目上编写的React代码,您会发现它们将这些小事情应用到了整个地方。 因此,当您编写下一个React组件时,它们非常好学习和实现。

Thanks for reading

谢谢阅读

翻译自: https://levelup.gitconnected.com/small-tips-to-write-better-react-code-5230472e786f

react 代码编写原则

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React开发中,有一些小技巧可以帮助提高开发效率和代码质量。以下是一些常用的React开发小技巧: 1. 使用函数组件代替类组件:函数组件具有更简洁的语法和更好的性能,在不需要使用生命周期方法和状态管理的情况下,优先考虑使用函数组件来编写代码。 2. 使用React Fragments来包裹组件:React Fragments可以帮助我们避免多余的DOM节点,提高代码的可读性和性能。 3. 使用解构赋值来获取props:使用解构赋值可以更方便地获取和使用props,使代码更简洁。 4. 使用箭头函数来定义组件方法:箭头函数可以解决绑定this的问题,使代码更简洁易读。 5. 使用条件渲染来控制组件显示:使用条件渲染可以根据不同的条件来显示不同的组件或内容,提高代码的灵活性和可复用性。 6. 使用ES6的模板字符串来拼接字符串:使用模板字符串可以更方便地拼接字符串,避免繁琐的字符串拼接操作。 7. 使用PropTypes或TypeScript来进行类型检查:使用PropTypes或TypeScript可以帮助我们在开发过程中及时发现潜在的类型错误,提高代码的健壮性和可维护性。 8. 使用React DevTools进行调试:React DevTools是一个强大的调试工具,可以帮助我们分析组件的渲染过程、性能优化和状态管理等问题。 这些小技巧可以使React开发更加高效和优雅。但需要根据具体的项目需求和个人经验选择合适的技巧来应用。 <span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [React 开发必须知道的 34个技巧](https://blog.csdn.net/sinat_17775997/article/details/117035521)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值