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

在这里插入图片描述
前端开发中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' 30const [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.mzph.cn/news/818746.shtml

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

相关文章

线性表概念及顺序表的实现

文章目录 前言一、线性表1.定义2.特点3.一般线性表的抽象数据类型定义 二、线性表的顺序存储&#xff08;顺序表&#xff09;1.基本概念2.数组实现顺序表3.顺序表中基本操作的具体实现4.顺序表总结 总结 前言 T_T此专栏用于记录数据结构及算法的&#xff08;痛苦&#xff09;学…

MyBatis 源码分析系列文章导读

1.本文速览 本篇文章是我为接下来的 MyBatis 源码分析系列文章写的一个导读文章。本篇文章从 MyBatis 是什么&#xff08;what&#xff09;&#xff0c;为什么要使用&#xff08;why&#xff09;&#xff0c;以及如何使用&#xff08;how&#xff09;等三个角度进行了说明和演…

vue--数据代理与数据劫持

0.回顾Object.defineProperty()方法 let number 18let person {name:张三,sex:男,}Object.defineProperty(person,age,{// value:18,// enumerable:true, //控制属性是否可以枚举&#xff0c;默认值是false// writable:true, //控制属性是否可以被修改&#xff0c;默认值是fa…

通义灵码×西安交通大学携手打造“云工开物-高校训练营”,解锁 AI 时代编程学习与实战

作为大学生如何利用 AI “整活儿”&#xff1f;欢迎各位同学关注阿里云与西安交通大学计算机学院携手打造的“云工开物-高校训练营”&#xff0c;带你走近 AI 编程助手“通义灵码”。通义灵码是阿里推出的免费 AI 编程工具&#xff0c;拥有实时代码续写与优化、自然语言生成代码…

记一次对某高校微信小程序的漏洞挖掘

挖掘目标的部署在微信的资产(减少信息的收集&#xff0c;毕竟一般web站点没有账号密码不好进入后台&#xff0c;挖掘功能点少) 寻找目标的微信小程序(非原图) 招生小程序打不开&#xff0c;只能挖掘管理系统 进入后发现存在上报安全隐患功能&#xff0c;可以上传图片 准备上传…

浅谈Java21的新特性-虚拟线程

虚拟线程&#xff08;Virtual Threads&#xff09;&#xff0c;又称为用户模式线程&#xff08;User-Mode Threads&#xff09;或纤程&#xff08;Fibers&#xff09;&#xff0c;是一种高级线程模型&#xff0c;在Java等现代编程语言环境中引入&#xff0c;旨在简化并发编程并…

Vue的图片懒加载 vue-lazyload插件使用

图片懒加载是一种网页性能优化技术&#xff0c;页面加载时仅加载可见区域内的图像&#xff0c;图像只会在用户滚动或浏览到它们时才会被加载&#xff0c;而不是在页面一开始就全部加载。 优点 可以减少首页首次加载的数量&#xff0c;减少服务器的压力有占位图片来展示预加载动…

【面经】操作系统/Linux

1、计算机的五大单元 电脑的五大单元包括&#xff1a;输入单元、输出单元、控制单元、算数逻辑单元、存储单元五大部分。其中CPU占有控制、算术逻辑单元&#xff0c;存储单元又包含内存与辅助内存&#xff1b; 2、什么是操作系统 操作系统&#xff1a;负责管理协调我们计算机…

Qt QStyle详解

1.简介 QStyle类是 Qt 框架中用于控制应用程序界面元素外观的一个抽象基类。这个类提供了一种方式来定制窗口部件&#xff08;widgets&#xff09;的绘制和行为&#xff0c;可以通过改变主题或风格来更改应用程序的外观&#xff0c;而无需修改窗口部件本身的代码。 Qt包含一组…

python爬虫------- Selenium下篇(二十三天)

&#x1f388;&#x1f388;作者主页&#xff1a; 喔的嘛呀&#x1f388;&#x1f388; &#x1f388;&#x1f388;所属专栏&#xff1a;python爬虫学习&#x1f388;&#x1f388; ✨✨谢谢大家捧场&#xff0c;祝屏幕前的小伙伴们每天都有好运相伴左右&#xff0c;一定要天天…

剑指offer03:数组中重复的数组---leetcode:LCR 120. 寻找文件副本

设备中存有 n 个文件&#xff0c;文件 id 记于数组 documents。若文件 id 相同&#xff0c;则定义为该文件存在副本。请返回任一存在副本的文件 id。 示例 1&#xff1a; 输入&#xff1a;documents [2, 5, 3, 0, 5, 0] 输出&#xff1a;0 或 5提示&#xff1a; 0 ≤ docume…

Python中的定长参数和不定长参数:深入理解与应用

文章目录 1. 定长参数的基本使用2. 不定长参数的基本使用2.1 *args 的使用2.2 **kwargs 的使用 3. 参数的混合使用4. 参数的应用实例4.1 数据处理示例4.2 事件处理示例小彩蛋... 函数参数的灵活处理是编写高效、可读性强的代码的关键。下面将详细介绍定长参数和不定长参数的使用…

【代码随想录算法训练营第四十八天 | LeetCode198.打家劫舍、213.打家劫舍II、337.打家劫舍III】

代码随想录算法训练营第四十八天 | LeetCode198.打家劫舍、213.打家劫舍II、337.打家劫舍III 一、198.打家劫舍 解题代码C&#xff1a; class Solution { public:int rob(vector<int>& nums) {if (nums.size() 0) return 0;if (nums.size() 1) return nums[0];ve…

CAN帧中的ACK位

1&#xff1a;先看官方文档对ACK的解释 All nodes that have received the matching CRC sequence (and, in FD Frames the matching stuff count) shall send an ACK within the ACK slot by overwriting the recessive bit of the transmitter by a dominant bit (they send…

求圆、圆球和圆柱的面积和体积(C语言)

一、运行结果&#xff1b; 二、源代码&#xff1b; # define _CRT_SECURE_NO_WARNINGS # include <stdio.h> //定义π常量的值&#xff1b; # define π 3.141526int main() {//初始化变量值&#xff1b;float r, h, S1, S2, P1, V1, V2;int judge 0;//提示用户&#x…

Python基于flask的豆瓣电影分析可视化系统

博主介绍&#xff1a;✌程序员徐师兄、7年大厂程序员经历。全网粉丝12w、csdn博客专家、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精彩专栏推荐订阅&#x1f447;…

第一天练习

一.在系统中设定延迟任务要求如下 在系统中建立easylee用户&#xff0c;设定其密码为easylee [rootxixi /]# useradd easylee [rootxixi /]# passwd easylee Changing password for user easylee. New password:easylee BAD PASSWORD: The password is shorter than 8 charac…

python 实现方差检验

前面介绍的 z z z检验和 t t t检验主要用于对总体的均值进行假设检验&#xff0c;下面主要介绍对总体方差进行假设检验的方法。 一. 单个总体方差检验 设总体 X ∼ N ( μ , δ 2 ) X\sim N(\mu, \delta^2) X∼N(μ,δ2)&#xff0c; μ , δ 2 \mu,\delta^2 μ,δ2均未知&am…

mid_360建图和定位

录制数据 roslaunch livox_ros_driver2 msg_MID360.launch使用fast-lio 建图 https://github.com/hku-mars/FAST_LIO.git 建图效果 使用python做显示 https://gitee.com/linjiey11/mid360/blob/master/show_pcd.py 使用 point_lio建图 https://github.com/hku-mars/Point…

【数据结构】【C++】AVL树的模拟实现(插入、判断、旋转)

文章目录 1 概念2 实现2.1 AVL树结点的定义2.2 AVL树的插入2.2.1 AVL树的插入规则2.2.2 旋转2.2.2.1 左单旋2.2.2.2 右单旋2.2.2.3 左右双旋2.2.2.4 右左双旋 2.2.3 总结 3 平衡判断4 删除5 源码 1 概念 二叉搜索树虽可以缩短查找的效率&#xff0c;但如果数据有序或接近有序二…