WHAT - React 学习系列(一)

官方文档

If you have a lot of HTML to port to JSX, you can use an online converter.

You’ll get two things from useState: the current state (count), and the function that lets you update it (setCount).

  • To “remember” things, components use state.
  • To make the UI interactive, you need to let users change your underlying data model. You will use state for this.

Which of these are state? Identify the ones that are not:

  • Does it remain unchanged over time? If so, it isn’t state.
  • Is it passed in from a parent via props? If so, it isn’t state.
  • Can you compute it based on existing state or props in your component? If so, it definitely isn’t state!

After identifying your app’s minimal state data, you need to identify which component is responsible for changing this state, or owns the state.
For each piece of state in your application:

  • Identify every component that renders something based on that state.
  • Find their closest common parent component—a component above them all in the hierarchy.
  • Decide where the state should live:
  • Often, you can put the state directly into their common parent.
  • You can also put the state into some component above their common parent.
  • If you can’t find a component where it makes sense to own the state, create a new component solely for holding the state and add it somewhere in the hierarchy above the common parent component.

You can find other built-in Hooks in the API reference.
Hooks are more restrictive than other functions. You can only call Hooks at the top of your components (or other Hooks). If you want to use useState in a condition or a loop, extract a new component and put it there.

A JSX element is a combination of JavaScript code and HTML tags that describes what you’d like to display.

To “escape into JavaScript” from JSX, you need curly braces. Add curly braces around value in JSX like so:

function Square({ value }) {return <button className="square">{value}</button>;
}

React DevTools let you check the props and the state of your React components.

When you were passing onSquareClick={handleClick}, you were passing the handleClick function down as a prop. You were not calling it! But now you are calling that function right away—notice the parentheses in handleClick(0) — and that’s why it runs too early. You don’t want to call handleClick until the user clicks! Instead, let’s do this: <Square value={squares[0]} onSquareClick={() => handleClick(0)} />. Notice the new () => syntax. Here, () => handleClick(0) is an arrow function, which is a shorter way to define functions.

In React, it’s conventional to use onSomething names for props which represent events and handleSomething for the function definitions which handle those events.

**Why immutability is important?**Note how in handleClick, you call .slice() to create a copy of the squares array instead of modifying the existing array?
https://react.dev/learn/tutorial-tic-tac-toe#why-immutability-is-important

You can learn more about how React chooses when to re-render a component in the memo API reference.
https://react.dev/reference/react/memo

When you render a list, React stores some information about each rendered list item. When you update a list, React needs to determine what has changed. You could have added, removed, re-arranged, or updated the list’s items. React is a computer program and does not know what you intended, so you need to specify a key property for each list item to differentiate each list item from its siblings. When a list is re-rendered, React takes each list item’s key and searches the previous list’s items for a matching key. If the current list has a key that didn’t exist before, React creates a component. If the current list is missing a key that existed in the previous list, React destroys the previous component. If two keys match, the corresponding component is moved.
https://react.dev/learn/tutorial-tic-tac-toe#picking-a-key

Using the array index as a key is problematic when trying to re-order a list’s items or inserting/removing list items?

To implement a UI in React, you will usually follow the same five steps.
Step 1: Break the UI into a component hierarchy
Step 2: Build a static version in React
Step 3: Find the minimal but complete representation of UI state
Step 4: Identify where your state should live
Step 5: Add inverse data flow
https://react.dev/learn/thinking-in-react

In simpler examples, it’s usually easier to go top-down, and on larger projects, it’s easier to go bottom-up.

You can learn all about handling events and updating state in the Adding Interactivity section.
https://react.dev/learn/adding-interactivity

  • Responding to events
  • State: a component’s memory
  • Render and commit
  • State as a snapshot
  • Queueing a series of state updates
  • Updating objects in state
  • Updating arrays in state

state as a snapshot:

console.log(count);  // 0
setCount(count + 1); // Request a re-render with 1
console.log(count);  // Still 0!

Read State as a Snapshot to learn why state appears “fixed” and unchanging inside the event handlers.
https://react.dev/learn/state-as-a-snapshot

updater function:

console.log(score);  // 0
setScore(score + 1); // setScore(0 + 1);
console.log(score);  // 0
setScore(score + 1); // setScore(0 + 1);
console.log(score);  // 0
setScore(score + 1); // setScore(0 + 1);
console.log(score);  // 0

can fix this by passing an updater function when setting state.

function increment() {setScore(s => s + 1);
}

update objects:

Usually, you will use the ... spread syntax to copy objects and arrays that you want to change.

  const [person, setPerson] = useState({name: 'Niki de Saint Phalle',artwork: {title: 'Blue Nana',city: 'Hamburg',image: 'https://i.imgur.com/Sd1AgUOm.jpg',}});function handleNameChange(e) {setPerson({...person,name: e.target.value});}function handleTitleChange(e) {setPerson({...person,artwork: {...person.artwork,title: e.target.value}});}

If copying objects in code gets tedious, you can use a library like Immer to reduce repetitive code:
GitHub - immerjs/use-immer: Use immer to drive state with a React hooks

  import { useImmer } from 'use-immer';const [person, updatePerson] = useImmer({name: 'Niki de Saint Phalle',artwork: {title: 'Blue Nana',city: 'Hamburg',image: 'https://i.imgur.com/Sd1AgUOm.jpg',}});function handleNameChange(e) {updatePerson(draft => {draft.name = e.target.value;});}function handleTitleChange(e) {updatePerson(draft => {draft.artwork.title = e.target.value;});}

update arrays:

Arrays are another type of mutable JavaScript objects you can store in state and should treat as read-only.

  const [list, setList] = useState(initialList);function handleToggle(artworkId, nextSeen) {setList(list.map(artwork => {if (artwork.id === artworkId) {return { ...artwork, seen: nextSeen };} else {return artwork;}}));}

If copying arrays in code gets tedious, you can use a library like Immer to reduce repetitive code:

import { useImmer } from 'use-immer';
const [list, updateList] = useImmer(initialList);function handleToggle(artworkId, nextSeen) {updateList(draft => {const artwork = draft.find(a =>a.id === artworkId);artwork.seen = nextSeen;});}

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

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

相关文章

淘宝卖家为啥不退差价怎么回事 淘宝客服不退差价

今天给各位分享淘宝卖家为啥不退差价怎么回事的知识&#xff0c;其中也会对淘宝客服不退差价进行解释&#xff0c;如果能碰巧解决你现在面临的问题&#xff0c;别忘了关注本站&#xff0c;现在开始吧&#xff01; [1] 拼多多商家不给差价怎么办 首先大家要跟商家进行商量&#…

LVS(Linux Virtual Server)集群,(1)NAT模式

Cluster&#xff1a;集群&#xff0c;为了解决某个特定问题将多台计算机组合起来形成的单个系统。 集群分为三种类型&#xff1a; LB(Load Balancing)&#xff0c;负载均衡&#xff0c;多个主机组成&#xff0c;每个主机只承担一部分访问请求 HA(High Availiablity)&#xf…

洛杉矶裸机云服务器怎么用

洛杉矶裸机云服务器是一种结合了物理服务器性能和云服务灵活性的高性能计算服务。它为用户提供了高效、安全的计算和存储能力&#xff0c;特别适合需要大量数据处理和快速响应的应用。具体分析如下&#xff0c;rak部落小编为您整理发布洛杉矶裸机云服务器怎么用。 1. 硬件配置选…

c++常考笔记

一 什么是深拷贝&#xff0c;什么是浅拷贝&#xff1f;c 浅拷贝&#xff08;Shallow Copy&#xff09; 浅拷贝在C中是默认的复制方式&#xff0c;它复制对象的所有成员变量&#xff0c;但对于指针成员变量&#xff0c;仅复制指针的值&#xff08;即指向的地址&#xff09;&am…

IPython的使用技巧

1、解释说明 IPython是一个强大的Python交互式shell&#xff0c;它提供了丰富的功能&#xff0c;如自动补全、历史记录、内置帮助等。IPython使得在命令行下编写和测试Python代码变得更加方便和高效。 2、使用示例 安装IPython&#xff1a; pip install ipython启动IPython…

亲测5个电脑浏览器高效技巧,保证让你搜索效率倍增!

虽然我们每个人的电脑基本每天都会用到浏览器&#xff0c;但你会发现有的人用起浏览器就是噼里啪啦的&#xff0c;找他要个什么网站他都能快速找到&#xff0c;而有的人&#xff0c;经常打开的是广告搜索的网页&#xff0c;找不到搜索的答案非常慢。小编今天就来跟你分享一下我…

LeetCode 热题100 --哈希

哈希 哈希&#xff0c;有限空间映射一个无限的空间。在空间内&#xff0c;有序化进行快速查询。 用空间换时间。 1.两数之和 给定一个整数数组 nums 和一个整数目标值 target&#xff0c;请你在该数组中找出 和为目标值 target 的那 两个 整数&#xff0c;并返回它们的数组…

深度神经网络:开启人工智能的新篇章

在人工智能的浩瀚星空中&#xff0c;深度神经网络&#xff08;Deep Neural Networks, DNNs&#xff09;无疑是那颗最为璀璨夺目的星辰。自2006年深度学习的概念被重新发掘以来&#xff0c;深度神经网络凭借其强大的模式识别能力和卓越的数据处理效率&#xff0c;引领了人工智能…

【面试干货】Java中的访问修饰符与访问级别

【面试干货】Java中的访问修饰符与访问级别 1、public2、protected3、默认&#xff08;没有访问修饰符&#xff09;4、private &#x1f496;The Begin&#x1f496;点点关注&#xff0c;收藏不迷路&#x1f496; 在Java中&#xff0c;访问修饰符用于控制类、变量、方法和构造器…

MATLAB 中,fopen 和 fgetl 函数用于文件操作

逐行读文件内容 fopen 和 fgetl 读结构体 在 MATLAB 中&#xff0c;fopen 和 fgetl函数用于文件操作。 fopen 用于打开一个文件并返回一个文件标识符&#xff0c;而 fgetl 用于从该文件中读取一行文本。 对于 MATLAB R2018b 版本&#xff0c;这些函数的用法没有显著变化&a…

使用 BroadcastChannel 进行跨页面通信

在现代 Web 应用程序中&#xff0c;有时候我们需要在不同的页面之间进行通信&#xff0c;例如在一个页面上的操作需要更新另一个页面上的内容。这时候&#xff0c;BroadcastChannel 可以成为一个非常有用的工具。BroadcastChannel 允许我们在不同的浏览器标签页或者不同的窗口之…

哈尔滨高校哪些系统需要做等保

高校需要进行等保的系统类别 高校的信息系统安全等级保护工作是根据《网络安全法》和相关政策法规要求进行的&#xff0c;目的是保护信息化发展、维护国家信息安全&#xff0c;确保信息系统的安全稳定运行。根据等保2.0标准&#xff0c;高校的信息系统可以分为不同的安全等级&…

Java中的测试驱动开发(TDD)实践

Java中的测试驱动开发&#xff08;TDD&#xff09;实践 大家好&#xff0c;我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编&#xff0c;也是冬天不穿秋裤&#xff0c;天冷也要风度的程序猿&#xff01; 引言 测试驱动开发&#xff08;TDD&#xff09;是一种…

分享:MoneyPrinterTurbo只需一个视频主题或关键词全自动生成一个高清的短视频

MoneyPrinterTurbo是基于原有的MoneyPrinter项目进行优化和重构后推出的新版本。它利用先进的AI技术&#xff0c;通过用户提供的视频主题或关键词&#xff0c;全自动生成视频文案、素材、字幕以及背景音乐&#xff0c;并最终合成高清的短视频。 功能特性 AI智能文案生成&…

问题解决:Problem exceeding maximum token in azure openai (with java)

问题背景&#xff1a; Im doing a chat that returns queries based on the question you ask it in reference to a specific database. For this I use azure openai and Java in Spring Boot. 我正在开发一个聊天功能&#xff0c;该功能根据您针对特定数据库的提问返回查询…

学习新语言方法总结(一)

随着工作时间越长&#xff0c;单一语言越来越难找工作了&#xff0c;需要不停地学习新语言来适应&#xff0c;总结一下自己学习新语言的方法&#xff0c;这次以GO为例&#xff0c;原来主语言是PHP &#xff0c;自学GO 了解语言特性&#xff0c;知道他是干嘛的 go语言&#xff0…

Spring 面试题,静态代理和动态代理的区别是什么?什么是 AOP 编程?

在编程领域&#xff0c;代理模式是一种非常常见的设计模式&#xff0c;它的主要思想就是通过引入一个中介来控制对象的访问。而在Java的世界里&#xff0c;我们通常会遇到两种代理模式&#xff0c;也就是静态代理和动态代理。 首先&#xff0c;我们来理解一下静态代理。静态代理…

Golang | Leetcode Golang题解之第171题Excel列表序号

题目&#xff1a; 题解&#xff1a; func titleToNumber(columnTitle string) (number int) {for i, multiple : len(columnTitle)-1, 1; i > 0; i-- {k : columnTitle[i] - A 1number int(k) * multiplemultiple * 26}return }

PyTorch下的5种不同神经网络-一.AlexNet

1.导入模块 导入所需的Python库&#xff0c;包括图像处理、深度学习模型和数据加载 import osimport torchimport torch.nn as nnimport torch.optim as optimfrom torch.utils.data import Dataset, DataLoaderfrom PIL import Imagefrom torchvision import models, transf…

怎么添加网页到桌面快捷方式?

推荐用过最棒的学习网站&#xff01;https://offernow.cn 添加网页到桌面快捷方式&#xff1f; 很简单&#xff0c;仅需要两步&#xff0c;接下来以chrome浏览器为例。 第一步 在想要保存的网页右上角点击设置。 第二步 保存并分享-创建快捷方式&#xff0c;保存到桌面即可…