阅读 React 官方文档 Part-1
Published by powerfulyang on Jan 23, 2022
开启Concurrent模式
开启 Concurrent
模式,使用 ReactDOM.createRoot(rootElement).render(<App />)
替换 ReactDOM.render()
。
React state updates are classified into two categories:
- Urgent updates — They reflect direct interaction, such as typing, clicking, pressing, dragging, etc.
- Transition updates — They transition the UI from one view to another.
source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
export function startTransition( scope: () => void, options?: StartTransitionOptions, ) { const prevTransition = ReactCurrentBatchConfig.transition; ReactCurrentBatchConfig.transition = {}; const currentTransition = ReactCurrentBatchConfig.transition; try { scope(); } finally { ReactCurrentBatchConfig.transition = prevTransition; } }
scope()
里的代码被标记为 Transition updates
Where can I use it?
You can use startTransition
to wrap any update that you want to move to the background. Typically, these type of updates fall into two categories:
- Slow rendering: These updates take time because React needs to perform a lot of work in order to transition the UI to show the results. Here is a real-world demo of adding
startTransition
to keep the app responsive in the middle of an expensive re-render. - Slow network: These updates take time because React is waiting for some data from the network. This use case is tightly integrated with Suspense.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
// Lane values below should be kept in sync with getLabelForLane(), used by react-devtools-timeline. // If those values are changed that package should be rebuilt and redeployed. export const TotalLanes = 31; export const NoLanes: Lanes = /* */ 0b0000000000000000000000000000000; export const NoLane: Lane = /* */ 0b0000000000000000000000000000000; export const SyncLane: Lane = /* */ 0b0000000000000000000000000000001; export const InputContinuousHydrationLane: Lane = /* */ 0b0000000000000000000000000000010; export const InputContinuousLane: Lane = /* */ 0b0000000000000000000000000000100; export const DefaultHydrationLane: Lane = /* */ 0b0000000000000000000000000001000; export const DefaultLane: Lane = /* */ 0b0000000000000000000000000010000; const TransitionHydrationLane: Lane = /* */ 0b0000000000000000000000000100000; const TransitionLanes: Lanes = /* */ 0b0000000001111111111111111000000; const TransitionLane1: Lane = /* */ 0b0000000000000000000000001000000; const TransitionLane2: Lane = /* */ 0b0000000000000000000000010000000; const TransitionLane3: Lane = /* */ 0b0000000000000000000000100000000; const TransitionLane4: Lane = /* */ 0b0000000000000000000001000000000; const TransitionLane5: Lane = /* */ 0b0000000000000000000010000000000; const TransitionLane6: Lane = /* */ 0b0000000000000000000100000000000; const TransitionLane7: Lane = /* */ 0b0000000000000000001000000000000; const TransitionLane8: Lane = /* */ 0b0000000000000000010000000000000; const TransitionLane9: Lane = /* */ 0b0000000000000000100000000000000; const TransitionLane10: Lane = /* */ 0b0000000000000001000000000000000; const TransitionLane11: Lane = /* */ 0b0000000000000010000000000000000; const TransitionLane12: Lane = /* */ 0b0000000000000100000000000000000; const TransitionLane13: Lane = /* */ 0b0000000000001000000000000000000; const TransitionLane14: Lane = /* */ 0b0000000000010000000000000000000; const TransitionLane15: Lane = /* */ 0b0000000000100000000000000000000; const TransitionLane16: Lane = /* */ 0b0000000001000000000000000000000; const RetryLanes: Lanes = /* */ 0b0000111110000000000000000000000; const RetryLane1: Lane = /* */ 0b0000000010000000000000000000000; const RetryLane2: Lane = /* */ 0b0000000100000000000000000000000; const RetryLane3: Lane = /* */ 0b0000001000000000000000000000000; const RetryLane4: Lane = /* */ 0b0000010000000000000000000000000; const RetryLane5: Lane = /* */ 0b0000100000000000000000000000000; export const SomeRetryLane: Lane = RetryLane1; export const SelectiveHydrationLane: Lane = /* */ 0b0001000000000000000000000000000; const NonIdleLanes: Lanes = /* */ 0b0001111111111111111111111111111; export const IdleHydrationLane: Lane = /* */ 0b0010000000000000000000000000000; export const IdleLane: Lane = /* */ 0b0100000000000000000000000000000; export const OffscreenLane: Lane = /* */ 0b1000000000000000000000000000000;
Why is isMounted() an anti-pattern and what is the proper solution?
The primary use case for isMounted()
is to avoid calling setState()
after a component has been unmounted, because it will emit a warning.
1 2 3
if (this.isMounted()) { this.setState({...}) }
Checking isMounted()
before calling setState()
does eliminate the warning, but it also defeats the purpose of the warning. Using isMounted()
is a code smell because the only reason you would check is because you think you might be holding a reference after the component has unmounted.
An optimal solution would be to find places where setState()
might be called after a component has unmounted, and fix them. Such situations most commonly occur due to callbacks, when a component is waiting for some data and gets unmounted before the data arrives. Ideally, any callbacks should be canceled in componentWillUnmount()
, prior to unmounting.
React keys
默认情况下,当递归 DOM 节点的子元素时,React 会同时遍历两个子元素的列表;当产生差异时,生成一个 mutation。
在子元素列表末尾新增元素时,更新开销比较小。比如:
1 2 3 4 5 6 7 8 9 10
<ul> <li>first</li> <li>second</li> </ul> <ul> <li>first</li> <li>second</li> <li>third</li> </ul>
React 会先匹配两个 <li>first</li>
对应的树,然后匹配第二个元素 <li>second</li>
对应的树,最后插入第三个元素的 <li>third</li>
树。
如果只是简单的将新增元素插入到表头,那么更新开销会比较大。比如:
1 2 3 4 5 6 7 8 9 10
<ul> <li>Duke</li> <li>Villanova</li> </ul> <ul> <li>Connecticut</li> <li>Duke</li> <li>Villanova</li> </ul>
React 并不会意识到应该保留 <li>Duke</li>
和 <li>Villanova</li>
,而是会重建每一个子元素。这种情况会带来性能问题。
为了解决上述问题,React 引入了 key
属性。当子元素拥有 key 时,React 使用 key 来匹配原有树上的子元素以及最新树上的子元素。以下示例在新增 key
之后,使得树的转换效率得以提高:
1 2 3 4 5 6 7 8 9 10
<ul> <li key="2015">Duke</li> <li key="2016">Villanova</li> </ul> <ul> <li key="2014">Connecticut</li> <li key="2015">Duke</li> <li key="2016">Villanova</li> </ul>
现在 React 知道只有带着 '2014'
key 的元素是新元素,带着 '2015'
以及 '2016'
key 的元素仅仅移动了。
实际开发中,编写一个 key 并不困难。你要展现的元素可能已经有了一个唯一 ID,于是 key 可以直接从你的数据中提取:
1
<li key={item.id}>{item.name}</li>
当以上情况不成立时,你可以新增一个 ID 字段到你的模型中,或者利用一部分内容作为哈希值来生成一个 key。这个 key 不需要全局唯一,但在列表中需要保持唯一。
最后,你也可以使用元素在数组中的下标作为 key。这个策略在元素不进行重新排序时比较合适,如果有顺序修改,diff 就会变慢。
当基于下标的组件进行重新排序时,组件 state 可能会遇到一些问题。由于组件实例是基于它们的 key 来决定是否更新以及复用,如果 key 是一个下标,那么修改顺序时会修改当前的 key,导致非受控组件的 state(比如输入框)可能相互篡改,会出现无法预期的变动。
在 Codepen 有两个例子,分别为 展示使用下标作为 key 时导致的问题,以及不使用下标作为 key 的例子的版本,修复了重新排列,排序,以及在列表头插入的问题。
如果你选择不指定显式的 key 值,那么 React 将默认使用索引用作为列表项目的 key 值。
实际上,JSX 仅仅只是 React.createElement(component, props, ...children)
函数的语法糖。如下 JSX 代码:
1 2 3
<MyButton color="blue" shadowSize={2}> Click Me </MyButton>
会编译为:
1 2 3 4 5
React.createElement( MyButton, {color: 'blue', shadowSize: 2}, 'Click Me' )
如果没有子节点,你还可以使用自闭合的标签形式,如:
1
<div className="sidebar" />
会编译为:
1 2 3 4
React.createElement( 'div', {className: 'sidebar'} )
如果你想测试一些特定的 JSX 会转换成什么样的 JavaScript,你可以尝试使用 在线的 Babel 编译器。
JSX 标签的第一部分指定了 React 元素的类型。
大写字母开头的 JSX 标签意味着它们是 React 组件。这些标签会被编译为对命名变量的直接引用,所以,当你使用 JSX <Foo />
表达式时,Foo
必须包含在作用域内。
由于 JSX 会编译为 React.createElement
调用形式,所以 React
库也必须包含在 JSX 代码作用域内。
例如,在如下代码中,虽然 React
和 CustomButton
并没有被直接使用,但还是需要导入:
1 2 3 4 5 6 7
import React from 'react'; import CustomButton from './CustomButton'; function WarningButton() { // return React.createElement(CustomButton, {color: 'red'}, null); return <CustomButton color="red" />; }
如果你不使用 JavaScript 打包工具而是直接通过 <script>
标签加载 React,则必须将 React
挂载到全局变量中。
在 JSX 中,你也可以使用点语法来引用一个 React 组件。当你在一个模块中导出许多 React 组件时,这会非常方便。例如,如果 MyComponents.DatePicker
是一个组件,你可以在 JSX 中直接使用:
1 2 3 4 5 6 7 8 9 10
import React from 'react'; const MyComponents = { DatePicker: function DatePicker(props) { return <div>Imagine a {props.color} datepicker here.</div>; } } function BlueDatePicker() { return <MyComponents.DatePicker color="blue" />;}
以小写字母开头的元素代表一个 HTML 内置组件,比如 <div>
或者 <span>
会生成相应的字符串 'div'
或者 'span'
传递给 React.createElement
(作为参数)。大写字母开头的元素则对应着在 JavaScript 引入或自定义的组件,如 <Foo />
会编译为 React.createElement(Foo)
。
我们建议使用大写字母开头命名自定义组件。如果你确实需要一个以小写字母开头的组件,则在 JSX 中使用它之前,必须将它赋值给一个大写字母开头的变量。
例如,以下的代码将无法按照预期运行:
1 2 3 4 5 6 7 8 9 10 11 12
import React from 'react'; // 错误!组件应该以大写字母开头: function hello(props) { // 正确!这种 <div> 的使用是合法的,因为 div 是一个有效的 HTML 标签 return <div>Hello {props.toWhat}</div>; } function HelloWorld() { // 错误!React 会认为 <hello /> 是一个 HTML 标签,因为它没有以大写字母开头: return <hello toWhat="World" />; }
要解决这个问题,我们需要重命名 hello
为 Hello
,同时在 JSX 中使用 <Hello />
:
1 2 3 4 5 6 7 8 9 10 11 12
import React from 'react'; // 正确!组件需要以大写字母开头: function Hello(props) { // 正确! 这种 <div> 的使用是合法的,因为 div 是一个有效的 HTML 标签: return <div>Hello {props.toWhat}</div>; } function HelloWorld() { // 正确!React 知道 <Hello /> 是一个组件,因为它是大写字母开头的: return <Hello toWhat="World" />; }
你不能将通用表达式作为 React 元素类型。如果你想通过通用表达式来(动态)决定元素类型,你需要首先将它赋值给大写字母开头的变量。这通常用于根据 prop 来渲染不同组件的情况下:
1 2 3 4 5 6 7 8 9 10 11 12
import React from 'react'; import { PhotoStory, VideoStory } from './stories'; const components = { photo: PhotoStory, video: VideoStory }; function Story(props) { // 错误!JSX 类型不能是一个表达式。 return <components[props.storyType] story={props.story} />; }
要解决这个问题, 需要首先将类型赋值给一个大写字母开头的变量:
1 2 3 4 5 6 7 8 9 10 11 12 13
import React from 'react'; import { PhotoStory, VideoStory } from './stories'; const components = { photo: PhotoStory, video: VideoStory }; function Story(props) { // 正确!JSX 类型可以是大写字母开头的变量。 const SpecificStory = components[props.storyType]; return <SpecificStory story={props.story} />; }
有多种方式可以在 JSX 中指定 props。
你可以把包裹在 {}
中的 JavaScript 表达式作为一个 prop 传递给 JSX 元素。例如,如下的 JSX:
1
<MyComponent foo={1 + 2 + 3 + 4} />
在 MyComponent
中,props.foo
的值等于 1 + 2 + 3 + 4
的执行结果 10
。
if
语句以及 for
循环不是 JavaScript 表达式,所以不能在 JSX 中直接使用。但是,你可以用在 JSX 以外的代码中。比如:
1 2 3 4 5 6 7 8 9
function NumberDescriber(props) { let description; if (props.number % 2 == 0) { description = <strong>even</strong>; } else { description = <i>odd</i>; } return <div>{props.number} is an {description} number</div>; }
你可以将字符串字面量赋值给 prop。如下两个 JSX 表达式是等价的:
1 2 3
<MyComponent message="hello world" /> <MyComponent message={'hello world'} />
当你将字符串字面量赋值给 prop 时,它的值是未转义的。所以,以下两个 JSX 表达式是等价的:
1 2 3
<MyComponent message="<3" /> <MyComponent message={'<3'} />
这种行为通常是不重要的,这里只是提醒有这个用法。
如果你没给 prop 赋值,它的默认值是 true
。以下两个 JSX 表达式是等价的:
1 2 3
<MyTextBox autocomplete /> <MyTextBox autocomplete={true} />
通常,我们不建议不传递 value 给 prop,因为这可能与 ES6 对象简写混淆,{foo}
是 {foo: foo}
的简写,而不是 {foo: true}
。这样实现只是为了保持和 HTML 中标签属性的行为一致。
如果你已经有了一个 props 对象,你可以使用展开运算符 ...
来在 JSX 中传递整个 props 对象。以下两个组件是等价的:
1 2 3 4 5 6 7
function App1() { return <Greeting firstName="Ben" lastName="Hector" />; } function App2() { const props = {firstName: 'Ben', lastName: 'Hector'}; return <Greeting {...props} />;}
你还可以选择只保留当前组件需要接收的 props,并使用展开运算符将其他 props 传递下去。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
const Button = props => { const { kind, ...other } = props; const className = kind === "primary" ? "PrimaryButton" : "SecondaryButton"; return <button className={className} {...other} />; }; const App = () => { return ( <div> <Button kind="primary" onClick={() => console.log("clicked!")}> Hello World! </Button> </div> ); };
在上述例子中,kind
的 prop 会被安全的保留,它将不会被传递给 DOM 中的 <button>
元素。 所有其他的 props 会通过 ...other
对象传递,使得这个组件的应用可以非常灵活。你可以看到它传递了一个 onClick
和 children
属性。
属性展开在某些情况下很有用,但是也很容易将不必要的 props 传递给不相关的组件,或者将无效的 HTML 属性传递给 DOM。我们建议谨慎的使用该语法。
包含在开始和结束标签之间的 JSX 表达式内容将作为特定属性 props.children
传递给外层组件。有几种不同的方法来传递子元素:
你可以将字符串放在开始和结束标签之间,此时 props.children
就只是该字符串。这对于很多内置的 HTML 元素很有用。例如:
1
<MyComponent>Hello world!</MyComponent>
这是一个合法的 JSX,MyComponent
中的 props.children
是一个简单的未转义字符串 "Hello world!"
。因此你可以采用编写 HTML 的方式来编写 JSX。如下所示:
1
<div>This is valid HTML & JSX at the same time.</div>
JSX 会移除行首尾的空格以及空行。与标签相邻的空行均会被删除,文本字符串之间的新行会被压缩为一个空格。因此以下的几种方式都是等价的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<div>Hello World</div> <div> Hello World </div> <div> Hello World </div> <div> Hello World </div>
子元素允许由多个 JSX 元素组成。这对于嵌套组件非常有用:
1 2 3 4
<MyContainer> <MyFirstComponent /> <MySecondComponent /> </MyContainer>
你可以将不同类型的子元素混合在一起,因此你可以将字符串字面量与 JSX 子元素一起使用。这也是 JSX 类似 HTML 的一种表现,所以如下代码是合法的 JSX 并且也是合法的 HTML:
1 2 3 4 5 6 7
<div> Here is a list: <ul> <li>Item 1</li> <li>Item 2</li> </ul> </div>
React 组件也能够返回存储在数组中的一组元素:
1 2 3 4 5 6 7 8 9
render() { // 不需要用额外的元素包裹列表元素! return [ // 不要忘记设置 key :) <li key="A">First item</li>, <li key="B">Second item</li>, <li key="C">Third item</li>, ]; }
JavaScript 表达式可以被包裹在 {}
中作为子元素。例如,以下表达式是等价的:
1 2 3
<MyComponent>foo</MyComponent> <MyComponent>{'foo'}</MyComponent>
这对于展示任意长度的列表非常有用。例如,渲染 HTML 列表:
1 2 3 4 5 6 7 8 9 10 11 12
function Item(props) { return <li>{props.message}</li>; } function TodoList() { const todos = ['finish doc', 'submit pr', 'nag dan to review']; return ( <ul> {todos.map((message) => <Item key={message} message={message} />)} </ul> ); }
JavaScript 表达式也可以和其他类型的子元素组合。这种做法可以方便地替代模板字符串:
1 2 3
function Hello(props) { return <div>Hello {props.addressee}!</div>; }
通常,JSX 中的 JavaScript 表达式将会被计算为字符串、React 元素或者是列表。不过,props.children
和其他 prop 一样,它可以传递任意类型的数据,而不仅仅是 React 已知的可渲染类型。例如,如果你有一个自定义组件,你可以把回调函数作为 props.children
进行传递:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
// 调用子元素回调 numTimes 次,来重复生成组件 function Repeat(props) { let items = []; for (let i = 0; i < props.numTimes; i++) { items.push(props.children(i)); } return <div>{items}</div>; } function ListOfTenThings() { return ( <Repeat numTimes={10}> {(index) => <div key={index}>This is item {index} in the list</div>} </Repeat> ); }
你可以将任何东西作为子元素传递给自定义组件,只要确保在该组件渲染之前能够被转换成 React 理解的对象。这种用法并不常见,但可以用于扩展 JSX。
false
, null
, undefined
, and true
是合法的子元素。但它们并不会被渲染。以下的 JSX 表达式渲染结果相同:
1 2 3 4 5 6 7 8 9 10 11
<div /> <div></div> <div>{false}</div> <div>{null}</div> <div>{undefined}</div> <div>{true}</div>
这有助于依据特定条件来渲染其他的 React 元素。例如,在以下 JSX 中,仅当 showHeader
为 true
时,才会渲染 <Header />
组件:
1 2 3
<div> {showHeader && <Header />} <Content /> </div>
值得注意的是有一些 “falsy” 值,如数字 0
,仍然会被 React 渲染。例如,以下代码并不会像你预期那样工作,因为当 props.messages
是空数组时,将会渲染为数字 0
:
1 2 3 4 5
<div> {props.messages.length && <MessageList messages={props.messages} /> } </div>
要解决这个问题,确保 &&
之前的表达式总是布尔值:
1 2 3 4 5
<div> {props.messages.length > 0 && <MessageList messages={props.messages} /> } </div>
反之,如果你想渲染 false
、true
、null
、undefined
等值,你需要先将它们转换为字符串:
1 2 3
<div> My JavaScript variable is {String(myVariable)}. </div>