由于工作需要,最近开始学习 React,发现网上很难找到合适的学习资料,于是萌生了写 React16 新手上路系列的想法,主要是想分享一下我自己的学习过程。这系列大概会有10篇,预计四个月写完。
第一篇:常用基础知识
汇总我自己在边学边开发过程中经常用到的基础知识点以及在阅读官方文档的过程中记录下来的知识点,不一定全面。
组件
组件允许你将 UI 拆分为独立可复用的代码片段,并对每个片段进行独立构思。从概念上类似于 JavaScript 函数。它接受任意的入参(即 “props”),并返回用于描述页面展示内容的 React 元素。
函数式组件
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
class组件
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
数据来源和变动
props
不管是在函数式组件还是 Class 组件中,都不允许修改自身的 props。
props 有两种来源:
- defaultProps
- parent Component
state
state 是组件自身内部的可变状态。
setState
setState()
将对组件 state 的更改排入队列,并通知 React 需要使用更新后的 state 重新渲染此组件及其子组件。
将 setState()
视为请求而不是立即更新组件的命令。为了更好的感知性能,React 会延迟调用它,然后通过一次传递更新多个组件。React 并不会保证 state 的变更会立即生效。
setState()
并不总是立即更新组件。它会批量推迟更新。
setState
只有在 只有在合成事件和钩子函数中才是异步的,在原生事件和异步(setTimeout、.then等)中是同步的。
语法:
setState(updater, [callback])
updater
:一个对象或者一个函数
callback
:在 setState
完成合并并重新渲染组件后执行。通常,我们建议使用 componentDidUpdate()
来代替此方式。
生命周期
挂载
当组件实例被创建并插入 DOM 中时,其生命周期调用顺序如下:
constructor()
static getDerivedStateFromProps()
render()
componentDidMount()
更新
当组件的 props 或 state 发生变化时会触发更新。组件更新的生命周期调用顺序如下:
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
卸载
当组件从 DOM 中移除时会调用如下方法:
componentWillUnmount()
错误处理
当渲染过程,生命周期,或子组件的构造函数中抛出错误时,会调用如下方法:
static getDerivedStateFromError()
componentDidCatch()
事件处理
this的绑定
- bind:在
constructor
中利用 bind 绑定 this - 箭头函数:在回调中使用箭头函数绑定 this
- public class fields语法
参数传递
- 箭头函数
- bind
- 通过 data-attributes 传递参数
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
Refs
Refs 提供了一种方式,允许我们访问 DOM 节点或在 render 方法中创建的 React 元素。
有两种创建方式:
- createRef
- 回调refs
// createRef
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
// 回调Ref
class MyComponent1 extends React.Component {
constructor(props) {
super(props);
this.myRef = null
}
render() {
return <div ref={element => this.myRef = element} />;
}
}
Fragments
React 中的一个常见模式是一个组件返回多个元素。Fragments 允许你将子列表分组,而无需向 DOM 添加额外节点,可简写为空标签符( <>
)。