React 开发你需要了解的 JavaScript

2025-06-10

React 开发你需要了解的 JavaScript

你好,世界👋

欢迎阅读Kent C. Dodds 的 EpicReact.Dev 系列的第二篇评论,该系列文章基于Kent C. DoddsEpicReact.Dev研讨会资料。在上一篇文章中,您了解了EpicReact.Dev研讨会将涵盖的不同主题。如果您还没有阅读本系列的上一篇文章,请立即阅读并回来。在本文中,我将讲解在开始学习 React 之前需要了解的基本 JavaScript 概念。

Epic React:简介

让我们开始吧。


我是那种在学习 JavaScript 基本概念之前就学习 React 的人。正因为如此,在 React 之旅的早期,我甚至分不清代码中哪些部分是 React,哪些部分是原生 JavaScript。了解 JavaScript 的基本概念对于更好地理解 React 解决的难题至关重要。

在这篇博文中,我将介绍一些在使用 React 时经常用到的 JavaScript 概念。在深入学习 React 之前,最好先了解这些概念。

我将涵盖以下主题。您可以跳过您已经了解的主题。


逻辑与 (&&) 和逻辑或 (||) 运算符

逻辑与 (&&) 运算符

假设我们有以下表达式 - 其中bc表达式

b && c
Enter fullscreen mode Exit fullscreen mode

c仅当b真时,才会将其评估为的值,否则,它将被评估为的值b

笔记:

  • 如果b,则表达式c甚至不会被求值。
  • 这叫做shortcut evaluation
  • 这在使用 React 时会用到很多。

逻辑或(||)运算符

假设我们有以下表达式 - 其中bc表达式

b || c
Enter fullscreen mode Exit fullscreen mode

b如果 b 为,则其值将被评估为,否则,其值将被评估为c

笔记:

  • 快捷方式评估也在这里发生。
  • 如果b真值,那么表达式c甚至不会被求值。
  • 在使用 React 时你也会经常使用它。

模板字符串

这是创建字符串的新ES6方法。

让我们看一个例子。

假设您想要创建以下类型的字符串:

  • 3 blog posts were written by Bhanu Teja in a span of 2 weeks.

您将获得count(博客数量)、name(用户姓名)、span(所花费的时间跨度)作为变量。

不使用模板字面量

const count = 3
const user = 'Bhanu Teja'
const span = 2

const result = count + ' blog posts were written by ' 
                     + name + ' in a span of ' + span 
                     + ' weeks.'
Enter fullscreen mode Exit fullscreen mode

使用模板字面量

const count = 3
const name = 'Bhanu Teja'
const span = 2

const result = `${count} blog posts were written by ${name} in a span of ${span} weeks.`
Enter fullscreen mode Exit fullscreen mode

模板文字以 开始和结束backtick(`),您可以在其中写入文本字符串,并且必须用 和包裹JavaScript 表达式${}

让我们为上述示例添加另一个用例。

  • 如果我们只有 1 篇博文,则必须blog post使用blog posts
  • 如果时间跨度只有 1 周,则必须使用week而不是weeks

不使用模板字面量

function pluralize(text, count) {
    if (count === 1) {
        return text
    }
    return text + 's'
}

const result = count + ' ' + pluralize('blog post', count)  
                     + ' were written by ' + name
                     + ' in a span of ' + span 
                     + ' ' + pluralize('week', span) + '.'
Enter fullscreen mode Exit fullscreen mode

使用模板字面量

function pluralize(text, count) {
    if (count === 1) {
        return text
    }
    return text + 's'
}

const result = `${count} ${pluralize('blog post', count)} were written by ${name} in a span of ${span} ${pluralize('week', span)}.`
Enter fullscreen mode Exit fullscreen mode

三元运算符

这是 if-else 语句的简写形式。

最好用一个例子来解释这一点。

if (condition) {
    doSomething()
} else {
    doSomethingElse()
}
Enter fullscreen mode Exit fullscreen mode

上述示例使用三元运算符编写

condition ? doSomething() : doSomethingElse()
Enter fullscreen mode Exit fullscreen mode

句法

condition ? expressionIfTrue : expressionIfFalse
Enter fullscreen mode Exit fullscreen mode

简写属性名称

const id = 2
const name = 'Bhanu'
const count = 2

// This is the normal way
const user = {
    id: id,
    blogs: count,
    name: name,
}

// Using shorthand property names
const user = {
    id,
    blogs: count,
    name,
}
Enter fullscreen mode Exit fullscreen mode

如果的名称variable和对象的名称property相同,那么您可以只写变量名称并省略其余部分。

这是我最初学习 React 时不知道的事情之一,你通常会看到它在代码和文档中被大量使用。


对象解构

这是将对象的属性放入变量的一种简便方法。

// we have a `user` variable that looks like this
const user = {
    name: 'Bhanu Teja',
    blogs: 3,
    timeSpan: 2.
}

// without using object destructuring
const name = user.name
const blogs = user.blogs
const timeSpan = user.timeSpan

// using object destructuring
const { name, blogs, timeSpan } = user
Enter fullscreen mode Exit fullscreen mode

注意
解构变量的名称应该与对象属性的名称相同。


数组解构

这是将数组元素放入变量的简便方法。

// we have a `name` variable that looks like this
const name = [ 'Bhanu Teja', 'P']

// without using array destructuring
const firstName = name[0]
const lastName = name[1]

// using array destructuring
const [firstName, lastName] = name
Enter fullscreen mode Exit fullscreen mode

默认参数

如果在调用函数时未传递函数参数,您通常希望函数参数采用一些默认值。

让我们看一个例子

function sum(a = 2, b = 5) {
    return a + b
}

sum(5, 7) // a = 5, b = 7, result = 12
sum(4) // a = 4, b = 5(default value of b), result = 9
sum() // a = 2(default a), b = 5(default b), result = 7
Enter fullscreen mode Exit fullscreen mode

因此,每当您希望参数采用默认值时,只需=在参数后添加一个符号,然后在那里添加默认值。


可选链式调用

这是 javascript 的一个相对较新的特性。

可选链接运算符(?。)允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。

考虑表达式a?.b

a.b如果anot null且,则该表达式计算结果为not undefined,否则计算结果为undefined

您甚至可以多次链接此操作,例如a?.b?.c

  • 如果aundefinednull,则此表达式计算结果为undefined
  • 否则,如果b未定义或null,则此表达式的计算结果为undefined
  • 否则计算结果为a.b.c

句法:

obj.val?.prop
obj.val?.[expr]
obj.arr?.[index]
obj.func?.(args)
Enter fullscreen mode Exit fullscreen mode

空值合并运算符

空值合并运算符 (??) 是一个逻辑运算符,当其左侧操作数为null或时,返回其右侧操作数undefined,否则返回其左侧操作数。

考虑表达式a ?? b如果或,
则计算结果为;否则,计算结果为banullundefineda


扩展运算符

该运算符扩展可迭代对象的值。

数组扩展

const a = [1, 2, 3]
const b = [5, 6]

console.log(...a) // 1 2 3

// Now, if you want to have an array with values 0, 1, 2, 3, 4, 5, 6
const c = [0, ...a, 4, ...b]

console.log(c) // 0 1 2 3 4 5 6
Enter fullscreen mode Exit fullscreen mode

对象传播

const first = {a: 1, b: 2}
const second = {c: 3}


// Now to create an object {a: 1, b: 2, c: 3, d: 4}
const result = {...first, ...second, d: 4}

console.log(result) // {a: 1, b: 2, c: 3, d: 4}
Enter fullscreen mode Exit fullscreen mode

休息操作员

剩余参数语法允许我们将不确定数量的参数表示为数组。

函数参数

function sum(a, b, ...rest) {
    // ...
}

sum(1, 2, 3, 4, 5, 6) // a = 1, b = 2, rest = [3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

与对象一起使用

const user = {
    name: 'Bhanu Teja',
    blogs: 3,
    span: 2,
}
const {name, ...rest} = user
console.log(name) // Bhanu Teja
console.log(rest) // { blogs: 3, span: 2}
Enter fullscreen mode Exit fullscreen mode

箭头函数

这是 ES6 编写函数的新方法。

// without using arrow functions
const sum = function (a, b) {
    return a + b
}

// (or)

function sum (a, b) {
    return a + b
}

// Using arrow functions
const sum = (a, b) => {
    return a + b
}

// (or)

const sum = (a, b) => a+ b

const multiplyBy2 = (a) => a * 2

(or)

const multiplyBy2 = a => a * 2
Enter fullscreen mode Exit fullscreen mode

从上面的例子可以看出,将普通函数转换为箭头函数可以按如下方式完成:

  • 删除function关键字。
  • =>在参数后面添加一个。

笔记

  • 如果函数体是一个简单的表达式,你甚至可以省略return关键字,也不需要将它包裹在{和之间}
  • 如果只有一个参数,您可以选择删除参数周围的括号。
  • 箭头函数和普通函数之间还有一些区别,请查看以下精彩文章以了解更多信息。

数组方法

数组方法有很多,但我们经常使用其中的一些。我将介绍以下数组方法。

  • 地图
  • 筛选
  • 减少
  • 种类
  • 包括
  • 拼接

数组 map() 方法

此方法通过为数组的每个元素调用一个函数,从现有数组创建一个新数组。

我一直记得这一点mapping the values in an array to some other values

让我们看一个例子。

const names = [
    { firstName: 'Bhanu Teja', lastName: 'P' },
    { firstName: 'Florin', lastName: 'Pop'},
    { firstName: 'Brad', lastName: 'Traversy'},
]

// Let's say we have to create a new array with full names.

// First let's write a callback function which takes an array element as an argument.
function callback(name) {
    return name.firstName + ' ' + name.lastName
}

// Now let's call .map() method on the array
console.log(names.map(callback)) // ["Bhanu Teja P", "Florin Pop", "Brad Traversy"]

// You can even inline the callback function which is how most of the people write this.
names.map(function(name) { return name.firstName + ' ' + name.lastName })

// Let's write the same using arrow functions and template literals that we just learned earlier
names.map((name) => `${name.firstName} ${name.lastName}`)

// You can even omit the parenthesis around name
names.map(name => `${name.firstName} ${name.lastName}`)

// Let's use object destructuring
names.map(({firstName, lastName}) => `${firstName} ${lastName}`)
Enter fullscreen mode Exit fullscreen mode

句法:

// callback takes a single array element as an argument.
// values is an array
values.map(callback)
Enter fullscreen mode Exit fullscreen mode

笔记:

  • 调用此方法不会改变原始数组

数组 filter() 方法

现在我们知道了这个Array map方法,理解其他数组方法就很容易了。它们都有类似的语法。

数组过滤方法创建一个满足某些给定条件的元素的新数组。

我一直记得这一点,因为该filter方法会过滤掉不满足条件的元素。

// consider the following array of users
const users = [
    {id: 1, posts: 2},
    {id: 2, posts: 1},
    {id: 3, posts: 5},
    {id: 4, posts: 4},
    {id: 5, posts: 3},
]

// Let's say we want to have all users who have at least 3 posts.
users.filter((user) => user.posts >= 3) // [{id: 3, posts: 5}, {id: 4, posts: 4}, {id: 5, posts: 3}]
Enter fullscreen mode Exit fullscreen mode

句法:

// callback takes a single array element as an argument.
// values is an array
values.filter(callback)
Enter fullscreen mode Exit fullscreen mode

笔记:

  • 调用此方法不会改变原始数组

数组 reduce() 方法

数组 reduce 方法将数组中的值缩减为单个值。它对数组中的每个值执行回调函数。

在看示例之前,让我们先看看 reduce 方法的语法。

array.reduce(function(totalValue, currentValue, currentIndex, arr), initialValue)
Enter fullscreen mode Exit fullscreen mode
const values = [2, 4, 6, 7, 8]

// Let's say that we want to have a sum of all these values.
// Let's see how we do it using a traditional for loop
let total = 0
for(let i = 0; i < values.length; i++) {
    const value = values[i]
    total = total + value
}
console.log(total)


// Let's use reduce method now
const initialValue = 0
values.reduce((total, currentValue) => total + currentValue, initialValue)
Enter fullscreen mode Exit fullscreen mode

笔记:

  • initialValue是可选参数。
  • 调用此方法不会改变原始数组

数组sort()方法

回调函数接受两个不同的值作为参数。根据回调函数的返回值,决定两个元素的位置。

  • 如果返回值为负数,则认为第一个值在第二个值之前。
  • 如果返回值为零,则值的顺序将不会改变。
  • 如果返回值为正数,则认为第一个值在第二个值之后。
const values = [4, 10, 2, 1, 55]

// Let's say we want to sort this array in descending order
// so if a and b are given
// a should be before b if a > b
// a should be after b if a < b
// a and b can be at their own places if a === b

values.sort((a, b) => {
    if(a > b) {
        return -1
    }
    if(a < b) {
        return 1
    }
    return 0
}) // [55, 10, 4, 2, 1]


// You can also do this as follows
values.sort((a, b) => b - a)
Enter fullscreen mode Exit fullscreen mode

笔记:

  • 函数的返回值是排序后的数组
  • 这会改变原始数组
  • 如果您不传递任何回调函数,则会将值按字符串按升序排序。

数组 includes() 方法

true如果元素包含在数组中则返回,否则返回 false。
语法:

array.includes(element)
Enter fullscreen mode Exit fullscreen mode
const values = [2, 3, 4]
values.includes(1) // false
values.includes(2) // true
Enter fullscreen mode Exit fullscreen mode

笔记:

  • 您可以传递一个可选参数来指定开始搜索的起始索引。array.includes(element, startIndex)

数组 slice() 方法

句法

array.slice(start, end)
Enter fullscreen mode Exit fullscreen mode

数组切片将返回给定范围内的元素。

  • 开始
    • 从中选择元素的起始索引
    • 这是一个可选参数,默认情况下,其值为 0
    • 您甚至可以传递一个负数。
    • 负数代表距离末尾的位置。
      • -1指的是数组的最后一个元素,-2指的是倒数第二个元素,依此类推。
  • 结尾
    • 结束索引到选择元素的位置
    • 这是一个可选参数。如果不传递,则将选择直到数组末尾的所有元素。
    • 处的元素end将不会被选中
    • 这也接受负数作为参数,其含义与以前相同。
const numbers = [0, 1, 2, 3, 4, 5, 6, 7]
console.log(numbers.slice())  // [0, 1, 2, 3, 4, 5, 6, 7]
console.log(numbers.slice(2)) // [2, 3, 4, 5, 6, 7]
console.log(numbers.slice(2, 6)) // [2, 3, 4, 5]
console.log(numbers.slice(-1)) // [7]
console.log(numbers.slice(-3)) // [5, 6, 7]
console.log(numbers.slice(-3, -1)) // [5, 6]
Enter fullscreen mode Exit fullscreen mode

笔记:

  • 这不会改变原始数组

数组 splice() 方法

句法:

array.splice(index, count, item1, ....., itemX)
Enter fullscreen mode Exit fullscreen mode

此方法用于添加或删除数组中的元素。

  • 指数
    • 需要添加或移除元素的索引。也可以为负值。
  • 数数
    • 要删除的元素的数量。
  • 项目1,.....,项目X
    • 将在以下位置添加的项目index
const numbers = [0, 1, 2, 100, 6, 7]
// let's say we have to convert this array to [0, 1, 2, 3, 4, 5, 6, 7]
numbers.splice(3, 1, 3, 4, 5) 
console.log(numbers) // [0, 1, 2, 3, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode

笔记:

  • splice 方法的返回值是被移除的项目数组。
  • 这会改变原始数组

要了解有关不同数组方法的更多信息,请查看Aman Tyagi制作的精彩系列《Javascript 数组方法》


默认导出 vs 命名导出

在使用 React 时,你经常会用到 ES 模块的导入和导出。重要的是要知道如何在默认导出和命名导出时导入它们。

请查看以下精彩文章来了解这些内容。


承诺

你还需要了解 Promise 是什么以及如何使用它们。它们在 React 中会经常使用。

请参阅Kent C. Dodds这篇文章以了解更多相关信息。


基本 DOM 文档 API

熟悉诸如等基本文档 API 也是很好的createElementgetElementById如果您了解这些,您就会明白 React API 和文档 API 之间的异同。

如果您已经使用 javascript 一段时间了,那么您很可能已经了解基本的文档 API。

MDN Docs 是阅读这些内容的最佳场所。


您可能已经了解我在本文中解释的一些主题。即使您之前不了解,现在也了解了。这些概念足以帮助您跟上EpicReact系列的学习。如果您发现本文中可以改进或添加的内容,请随时发表评论。我会尽力采纳您的建议。如果您不想错过本系列的下一篇文章,请订阅我的博客。

下一步

在下一篇文章中,我们实际上要开始研讨会——从React Fundamentals研讨会开始。

下次再见👋


如果这篇文章对您有帮助,请点赞分享,以便其他人也能看到。如果您想通过电子邮件接收我的最新文章通知,请点击博客顶部的“订阅”按钮订阅我的博客。您也可以在 Twitter 上关注我@pbteja1998


您可能还喜欢以下文章:


如果您想了解更多关于本文提到的主题,可以阅读我在@Hashnode上找到的以下文章我会陆续添加更多文章到此列表。不同的人会找到不同的更好的解释。


科菲

鏂囩珷鏉ユ簮锛�https://dev.to/pbteja1998/epic-react-javascript-you-need-to-know-for-react-2o87
PREV
✨2021 年热门 React 图表库:react-chartjs-2
NEXT
Kubernetes 安全最佳实践