一文掌握 React 开发中的 JavaScript 基础知识

news2025/3/16 19:10:40

在这里插入图片描述
前端开发中JavaScript是基石。在 React 开发中掌握掌握基础的 JavaScript 方法将有助于编写出更加高效、可维护的 React 应用程序。

在 React 开发中使用 ES6 语法可以带来更简洁、可读性更强、功能更丰富,以及更好性能和社区支持等诸多好处。这有助于提高开发效率,并构建出更加优秀的 React 应用程序。

原生JavaScript基础

  1. 数组方法:
// map()
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map(num => num * 2);
console.log(doubledNumbers); // [2, 4, 6, 8, 10]

// filter()
const words = ['apple', 'banana', 'cherry', 'date'];
const fruitsWithA = words.filter(word => word.includes('a'));
console.log(fruitsWithA); // ['apple', 'banana', 'date']

// reduce()
const scores = [80, 85, 90, 92];
const totalScore = scores.reduce((acc, score) => acc + score, 0);
console.log(totalScore); // 347
  1. 字符串方法:
// split()/join()
const sentence = 'The quick brown fox jumps over the lazy dog.';
const words = sentence.split(' ');
console.log(words); // ['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog.']
const newSentence = words.join('-');
console.log(newSentence); // 'The-quick-brown-fox-jumps-over-the-lazy-dog.'

// substring()/substr()
const longString = 'This is a long string with some information.';
const shortString = longString.substring(10, 20);
console.log(shortString); // 'long strin'
  1. 对象方法:
// Object.keys()/Object.values()/Object.entries()
const person = { name: 'John Doe', age: 30, email: 'john.doe@example.com' };
const keys = Object.keys(person);
console.log(keys); // ['name', 'age', 'email']
const values = Object.values(person);
console.log(values); // ['John Doe', 30, 'john.doe@example.com']
const entries = Object.entries(person);
console.log(entries); // [['name', 'John Doe'], ['age', 30], ['email', 'john.doe@example.com']]

// Object.assign()
const base = { id: 1, name: 'John' };
const extended = Object.assign({}, base, { email: 'john@example.com' });
console.log(extended); // { id: 1, name: 'John', email: 'john@example.com' }
  1. 函数方法:
// call()/apply()
function greet(greeting, name) {
  console.log(`${greeting}, ${name}!`);
}

greet.call(null, 'Hello', 'John'); // Hello, John!
greet.apply(null, ['Hi', 'Jane']); // Hi, Jane!

// bind()
const boundGreet = greet.bind(null, 'Howdy');
boundGreet('Alice'); // Howdy, Alice!
  1. 其他常用方法:
// console.log()/console.error()
console.log('This is a log message');
console.error('This is an error message');

// setTimeout()/setInterval()
setTimeout(() => {
  console.log('This message will be logged after 2 seconds');
}, 2000);

let count = 0;
const interval = setInterval(() => {
  console.log(`This message will be logged every second. Count: ${count}`);
  count++;
}, 1000);

// Clear the interval after 5 seconds
setTimeout(() => {
  clearInterval(interval);
  console.log('Interval cleared');
}, 5000);

在 React 开发中如使用基础的 JavaScript 方法

  1. 数组方法:
// map()
const items = ['item1', 'item2', 'item3'];
return (
  <ul>
    {items.map((item, index) => (
      <li key={index}>{item}</li>
    ))}
  </ul>
);

// filter()
const users = [
  { id: 1, name: 'John', age: 30 },
  { id: 2, name: 'Jane', age: 25 },
  { id: 3, name: 'Bob', age: 40 }
];
const adults = users.filter(user => user.age >= 18);

// reduce()
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 15
  1. 字符串方法:
// split()/join()
const name = 'John Doe';
const nameParts = name.split(' ');
console.log(nameParts); // Output: ['John', 'Doe']
const formattedName = nameParts.join(', '); // 'Doe, John'

// substring()/substr()
const longText = 'This is a long text with some information.';
const shortText = longText.substring(0, 10); // 'This is a '
  1. 对象方法:
// Object.keys()/Object.values()/Object.entries()
const user = { id: 1, name: 'John', email: 'john@example.com' };
const keys = Object.keys(user); // ['id', 'name', 'email']
const values = Object.values(user); // [1, 'John', 'john@example.com']
const entries = Object.entries(user); // [[id, 1], [name, 'John'], [email, 'john@example.com']]

// Object.assign()
const baseProps = { id: 1, name: 'John' };
const extendedProps = { ...baseProps, email: 'john@example.com' };
  1. 函数方法:
// call()/apply()
class Button extends React.Component {
  handleClick = function(e) {
    console.log(this.props.label);
  }.bind(this);

  render() {
    return <button onClick={this.handleClick}>{this.props.label}</button>;
  }
}

// bind()
class Button extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(e) {
    console.log(this.props.label);
  }

  render() {
    return <button onClick={this.handleClick}>{this.props.label}</button>;
  }
}
  1. 其他常用方法:
// console.log()/console.error()
console.log('This is a log message');
console.error('This is an error message');

// setTimeout()/setInterval()
componentDidMount() {
  this.timer = setInterval(() => {
    this.setState(prevState => ({ count: prevState.count + 1 }));
  }, 1000);
}

componentWillUnmount() {
  clearInterval(this.timer);
}

常用的 ES6 方法

  1. let/const:
let x = 5; // 块级作用域
const PI = 3.14159; // 不可重新赋值
  1. 箭头函数:
// 传统函数
const square = function(x) {
  return x * x;
};

// 箭头函数
const square = (x) => {
  return x * x;
};

// 简写
const square = x => x * x;
  1. 模板字面量:
const name = 'John';
const age = 30;
console.log(`My name is ${name} and I'm ${age} years old.`);
  1. 解构赋值:
const person = { name: 'John', age: 30, email: 'john@example.com' };
const { name, age } = person;
console.log(name, age); // 'John' 30

const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first, second, rest); // 1 2 [3, 4, 5]
  1. :
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

const john = new Person('John', 30);
john.greet(); // 'Hello, my name is John.'
  1. Promise:
const fetchData = () => {
  return new Promise((resolve, reject) => {
    // 模拟异步操作
    setTimeout(() => {
      resolve({ data: 'Hello, Promise!' });
    }, 2000);
  });
};

fetchData()
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
  1. async/await:
const fetchData = async () => {
  try {
    const response = await fetchData();
    console.log(response.data);
  } catch (error) {
    console.error(error);
  }
};

fetchData();
  1. Spread 运算符:
const numbers1 = [1, 2, 3];
const numbers2 = [4, 5, 6];
const allNumbers = [...numbers1, ...numbers2];
console.log(allNumbers); // [1, 2, 3, 4, 5, 6]

const person = { name: 'John', age: 30 };
const updatedPerson = { ...person, email: 'john@example.com' };
console.log(updatedPerson); // { name: 'John', age: 30, email: 'john@example.com' }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1598214.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

MongoDB 索引全攻略

目录 一、索引介绍 1.1 单字段索引 1.2 复合索引 1.3 多键索引 1.4 主键索引 1.5 TTL 索引 1.6 地理空间索引 1.7 哈希索引 1.8 创建索引时注意事项 1.9 索引效果查看 二、索引实现原理 2.1 为什么使用 B-Tree 三、执行计划 一、索引介绍 任何数据库都有索引这一核心功能&…

Centos7.6部署minikube

1、什么是minikube ? Minikube是由Kubernetes社区维护的单机版的Kubernetes集群&#xff0c;支持macOS, Linux, and Windows等多种操作系统平台&#xff0c;使用最新的官方stable版本&#xff0c;并支持Kubernetes的大部分功能&#xff0c;从基础的容器编排管理&#xff0c;到…

基于AutoCAD的WMTS服务加载方法与应用研究

"针对在AutoCAD中加载地图存在数据定位操作复杂、数据渲染效率低、无法接入第三方地理信息服务的问题&#xff0c;提出了在AutoCAD中加载OGC标准的网络地图分块服务方法。基于ObjectARX二次开发插件&#xff0c;实现在AutoCAD中加载WMTS服务&#xff0c;兼容了第三方地理信…

基于Springboot的旅游管理系统

基于SpringbootVue的旅游管理系统的设计与实现 开发语言&#xff1a;Java数据库&#xff1a;MySQL技术&#xff1a;SpringbootMybatis工具&#xff1a;IDEA、Maven、Navicat 系统展示 用户登录 首页展示 旅游方案展示 旅游资讯 后台管理员登录 后台管理页面首页 用户管理 …

【自动驾驶】贝叶斯算法在机器学习中的应用研究

目录 第一章&#xff1a;引言 1.1 贝叶斯算法在机器学习中的重要性 1.2 研究背景 1.3 研究目的 1.4 论文结构 第二章&#xff1a;贝叶斯算法概述 2.1 贝叶斯定理 2.2 贝叶斯算法分类 第三章&#xff1a;贝叶斯算法在机器学习中的应用 3.1 贝叶斯分类器 3.2 贝叶斯回…

SpringSecurity源码分析3--UserDetail部分

UserDetailsService.class DaoAuthenticationProvider.class AbstractUserDetailsAuthenticationProvider.class 一个允许子类重写和处理UserDetails对象的基AuthenticationProvider。该类旨在响应UsernamePasswordAuthenticationToken身份验证请求。 AuthenticationProvider…

Gartner 《2024安全和风险管理技术路线图》:高价值技术 DSP 进入广泛部署阶段

近期&#xff0c;Gartner 发布《2024年技术采用路线图&#xff1a;安全与风险管理》&#xff08;以下简称&#xff1a;《路线图》&#xff09;&#xff0c;该信息图表识别了全球企业正在采用的 44 种与安全相关的技术&#xff0c;并根据采用阶段、部署风险和企业价值进行了映射…

python中的列表、元组、字典、集合(字典篇)

数据类型定义符号访问元素是否可变是否重复是否有序列表 [ ]索引可变可重复有序元组&#xff08;&#xff09;索引不可变可重复有序字典{key&#xff1a;value}键可变可重复无序集合{ }可变不可重复无序 字典概念 在python语言中&#xff0c;字典属于内置容器类&#xff0c;其…

什么是云安全

云安全和网络安全有所不同&#xff0c;因为云安全一词 比网络安全更涵盖整个企业基础设施。一般来说&#xff0c;当人们提到云安全时&#xff0c;指的是第三方服务提供商提供的 IaaS 云环境。在这种情况下&#xff0c;云安全不仅包括网络安全工具&#xff0c;还包括服务器、容器…

C#基础|数据类型、变量

哈喽&#xff0c;你好啊&#xff0c;我是雷工&#xff01; 01 数据类型 数据类型是为了方便存储数据的&#xff0c;为了将数据按照不同的分类存储&#xff0c;所以引入数据类型。这个在PLC中已经很熟悉了。 数据类型的作用&#xff1a;就是为了更好地管理内存&#xff0c;为…

[C++][算法基础]求最小生成树(Prim)

给定一个 n 个点 m 条边的无向图&#xff0c;图中可能存在重边和自环&#xff0c;边权可能为负数。 求最小生成树的树边权重之和&#xff0c;如果最小生成树不存在则输出 impossible。 给定一张边带权的无向图 G(V,E)&#xff0c;其中 V 表示图中点的集合&#xff0c;E 表示图…

【深度学习】AI修图——DragGAN原理解析

1、前言 上一篇&#xff0c;我们讲述了StyleGAN2。这一篇&#xff0c;我们就来讲一个把StyleGAN2作为基底架构的DragGAN。DragGAN的作用主要是对图片进行编辑&#xff0c;说厉害点&#xff0c;可能和AI修图差不多。这篇论文比较新&#xff0c;发表自2023年 原论文&#xff1a…

拼多多容器文件修改自动上传

拼多多开放平台php环境是官方的linux容器&#xff0c;不能自己搭建ftp上传文件&#xff0c;每每有文件更新都挺麻烦。 有些功能测试不想每次都打包全部代码上去重新发布一次程序生成新的容器&#xff0c;那样太过麻烦和效率低。 一开始搞了一个php的文件管理工具上去&#xf…

高效解决Visual Studio Code中文乱码问题

文章目录 问题解决步骤 问题 Visual Studio Code新建一个文件编码方式总是默认GBK&#xff0c;如果我不修改成默认UTF-8&#xff0c;那么每次运行&#xff0c;如果有中文需要输出就会乱码&#xff01; 解决步骤 之后我会持续更新&#xff0c;如果喜欢我的文章&#xff0c;请记…

Apache DolphinScheduler 社区 3 月月报

各位热爱 DolphinScheduler 的小伙伴们&#xff0c;DolphinScheduler 社区月报开始更新啦&#xff01;这里将记录 DolphinScheduler 社区每月的重要更新。 社区为 DolphinScheduler 3.2.x 版本做了诸多功能改进和 bug 修复 DolphinScheduler 月度 Merge Stars 感谢以下小伙伴 …

腾讯云轻量应用服务器端口怎么打开?

腾讯云轻量应用服务器端口怎么打开&#xff1f;在轻量应用服务器控制台的防火墙中开启端口&#xff0c;本文腾讯云百科txybk.com以80端口为例&#xff0c;来详细说下轻量应用服务器端口打开教程&#xff0c;另外可以在腾讯云百科 txy.wiki 查看当前轻量服务器最新的优惠券和配置…

LSTM 循环神经网络原理深度解读与网络结构精细剖析

长短期记忆网络&#xff08;Long Short-Term Memory, LSTM&#xff09;是一种特殊的循环神经网络&#xff08;Recurrent Neural Network, RNN&#xff09;&#xff0c;设计用于解决长期依赖问题&#xff0c;特别是在处理时间序列数据时。 循环神经网络&#xff08;RNN&#xf…

jenkins(docker)安装及应用

jenkins Jenkins是一个开源的、提供友好操作界面的持续集成(CI)工具&#xff0c;起源于Hudson&#xff08;Hudson是商用的&#xff09;&#xff0c;主要用于持续、自动的构建/测试软件项目、监控外部任务的运行&#xff08;这个比较抽象&#xff0c;暂且写上&#xff0c;不做解…

【InternLM】LMDeploy部署实践

1. LMDeploy基本介绍 LMDeploy提供一站式的大模型压缩、部署和服务&#xff0c;其主要特点包括&#xff1a; 高效的推理速度。通过引入持久批处理(即连续批处理)、阻塞 KV 缓存、动态拆分与融合、张量并行、高性能 CUDA 内核等关键特性&#xff0c;提供了比 vLLM 高1.8倍的请…

从零开始写一个RTSP服务器(三)RTP传输H.264

目录 一、RTP封装1.1 RTP数据结构1.2 源码 二、H.264的RTP打包2.1 H.264格式2.2 H.264的RTP打包方式2.3 H.264 RTP包的时间戳计算2.4 源码 三、H.264 RTP打包的sdp描述四、测试 本篇文章目标&#xff0c;使用vlc打开sdp文件后&#xff0c;可以观看到视频数据 一、RTP封装 1.1 …