组件的生命周期

挂载

当组件实例被创建并插入 DOM 中时,其生命周期调用顺序如下:

  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()

componentWillMount() 之后将废弃

更新

当组件的 props 或 state 发生变化时会触发更新。组件更新的生命周期调用顺序如下:

  • static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

componentWillUpdate() 、 componentWillReceiveProps() 之后将被废弃

卸载

当组件从 DOM 中移除时会调用如下方法:

  • componentWillUnmount()

错误处理

当渲染过程,生命周期,或子组件的构造函数中抛出错误时,会调用如下方法:

  • static getDerivedStateFromError()
  • componentDidCatch()

组件还提供了一些额外的 API:

  • setState()
  • forceUpdate()

单独介绍

getDerivedStateFromProps

这个生命周期函数是为了替代 componentWillReceiveProps 存在的,所以在你需要使用componentWillReceiveProps的时候,就可以考虑使用getDerivedStateFromProps来进行替代了。

两者的参数不相同的,而getDerivedStateFromProps是一个静态函数,也就是这个函数不能通过this访问到class的属性,也并不推荐直接访问属性。

而是应该通过参数提供的nextProps以及prevState来进行判断,根据新传入的props来映射到state。

需要注意的是,如果props传入的内容不需要影响到你的state,那么就需要返回一个null,这个返回值是必须的,所以尽量将其写到函数的末尾。

static getDerivedStateFromProps(nextProps, prevState) {
const {type} = nextProps;
// 当传入的type发生变化的时候,更新state
if (type !== prevState.type) {
return {
type,
};
}
// 否则,对于state不进行任何操作
return null;
}

如果你的组件内部既需要修改自己的type,又需要接收从外部修改的type。

static getDerivedStateFromProps(nextProps, prevState) {
const {type} = nextProps;
// type可能由props驱动,也可能由state驱动,这样判断会导致state驱动的type被回滚
if (type !== prevState.type) {
return {
type,
};
}
// 否则,对于state不进行任何操作
return null;
}

在非必须的时候,摒弃这种写法。type要么由props驱动,要么完全由state驱动。

如果实在没有办法解耦,那么就需要一个hack来辅助:绑定props到state上。

constructor(props) {
super(props);
this.state = {
type: 0,
props,
}
}
static getDerivedStateFromProps(nextProps, prevState) {
const {type, props} = nextProps;
// 这段代码可能看起来非常混乱,这个props可以被当做缓存,仅用作判断
if (type !== props.type) {
return {
type,
props: {
type,
},
};
}
// 否则,对于state不进行任何操作
return null;
}

上面的代码可以保证在进行多数据源驱动的时候,状态能够正确改变。当然,这样的代码很多情况下是会影响到别人阅读你的代码的,对于维护造成了非常大的困难。

getSnapshotBeforeUpdate(prevProps, prevState)

getSnapshotBeforeUpdate() 在最近一次渲染输出(提交到 DOM 节点)之前调用。它使得组件能在发生更改之前从 DOM 中捕获一些信息(例如,滚动位置)。此生命周期的任何返回值将作为参数传递给 componentDidUpdate()。

此用法并不常见,但它可能出现在 UI 处理中,如需要以特殊方式处理滚动位置的聊天线程等。

应返回 snapshot 的值(或 null)。

class ScrollingList extends React.Component {
constructor(props) {
super(props);
this.listRef = React.createRef();
} getSnapshotBeforeUpdate(prevProps, prevState) {
// 我们是否在 list 中添加新的 items ?
// 捕获滚动位置以便我们稍后调整滚动位置。
if (prevProps.list.length < this.props.list.length) {
const list = this.listRef.current;
return list.scrollHeight - list.scrollTop;
}
return null;
} componentDidUpdate(prevProps, prevState, snapshot) {
// 如果我们 snapshot 有值,说明我们刚刚添加了新的 items,
// 调整滚动位置使得这些新 items 不会将旧的 items 推出视图。
//(这里的 snapshot 是 getSnapshotBeforeUpdate 的返回值)
if (snapshot !== null) {
const list = this.listRef.current;
list.scrollTop = list.scrollHeight - snapshot;
}
} render() {
return (
<div ref={this.listRef}>{/* ...contents... */}</div>
);
}
}

在上述示例中,重点是从 getSnapshotBeforeUpdate 读取 scrollHeight 属性,因为 “render” 阶段生命周期(如 render)和 “commit” 阶段生命周期(如 getSnapshotBeforeUpdate 和 componentDidUpdate)之间可能存在延迟。

Error boundaries

Error boundaries 是 React 组件,它会在其子组件树中的任何位置捕获 JavaScript 错误,并记录这些错误,展示降级 UI 而不是崩溃的组件树。Error boundaries 组件会捕获在渲染期间,在生命周期方法以及其整个树的构造函数中发生的错误。

如果 class 组件定义了生命周期方法 static getDerivedStateFromError()componentDidCatch() 中的任何一个(或两者),它就成为了 Error boundaries。通过生命周期更新 state 可让组件捕获树中未处理的 JavaScript 错误并展示降级 UI。

仅使用 Error boundaries 组件来从意外异常中恢复的情况;不要将它们用于流程控制。

static getDerivedStateFromError(error)

此生命周期会在后代组件抛出错误后被调用。 它将抛出的错误作为参数,并返回一个值以更新 state

class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
} static getDerivedStateFromError(error) {
// 更新 state 使下一次渲染可以显降级 UI
return { hasError: true };
} render() {
if (this.state.hasError) {
// 你可以渲染任何自定义的降级 UI
return <h1>Something went wrong.</h1>;
} return this.props.children;
}
}

注意:getDerivedStateFromError() 会在渲染阶段调用,因此不允许出现副作用。 如遇此类情况,请改用 componentDidCatch()。

componentDidCatch(error, info)

componentDidCatch() 会在“提交”阶段被调用,因此允许执行副作用。 它应该用于记录错误之类的情况:

class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
} static getDerivedStateFromError(error) {
// 更新 state 使下一次渲染可以显示降级 UI
return { hasError: true };
} componentDidCatch(error, info) {
// "组件堆栈" 例子:
// in ComponentThatThrows (created by App)
// in ErrorBoundary (created by App)
// in div (created by App)
// in App
logComponentStackToMyService(info.componentStack);
} render() {
if (this.state.hasError) {
// 你可以渲染任何自定义的降级 UI
return <h1>Something went wrong.</h1>;
} return this.props.children;
}
}

setState的异步操作

因为setState是异步的,所有有时setState后获取this.state数据并不准确,可以如下操作:

state = {
name:'initName'
} this.setState((state,props)=>{
console.log(state,props);
return {name:'name-change'};
}) const {name}=this.state;
this.setState({name:'name-change'},()=>{
console.log(this.state.name,name) // name-change initName
})

官方文档:https://zh-hans.reactjs.org/docs/react-component.html#static-getderivedstatefromprops

React.Component(V16.8.6)的更多相关文章

  1. webpack学习(六)—webpack+react+es6(第3篇)

    接上篇 : webpack学习(六)—webpack+react+es6(第2篇) 上篇其实是有问题的,问题在取服务器数据这块.this.props 表示那些一旦定义,就不再改变的特性,而 this. ...

  2. webpack学习(六)—webpack+react+es6(第2篇)

    接上篇        webpack学习(五)—webpack+react+es6(第1篇) 本文做个简单的图片加文字的页面.其中,配置文件跟上篇一致.项目结构: index.html <!DO ...

  3. webpack学习(五)—webpack+react+es6(第1篇)

    如果你看过webpack学习系列的前一个文章,接下来做的东西会比较简单 :webpack学习(四)— webpack-dev-server react发展的很快,现在大部分开发react相关的项目,都 ...

  4. React Autocomplete(自动完成输入)示例教程

    React Autocomplete示例教程是今天的主题.在现代Web开发中,使用React改善用户体验是很容易.自动完成的概念很简单.它是基于用户输入的建议列表.然后,用户可以按Enter键以完成短 ...

  5. React HOC(高阶组件)

    一.定义 高阶函数:函数接受函数作为输入,或者输出一个函数. 高阶组件:接受React组件作为输入,或是输出一个组件.即hocFactory:: W: React.Component => E: ...

  6. React介绍(讲人话)

    p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 21.0px "PingFang SC"; color: #616161 } span. ...

  7. 学习React系列(一)——React.Component 生命周期

    挂载中(只执行一次) 以下方法在组件实例正被创建和插入到DOM中时调用 constructor()一般用于初始化state和方法的this绑定 componentWillMount() render( ...

  8. React.Component 与 React.PureComponent(React之性能优化)

    前言 先说说 shouldComponentUpdate 提起React.PureComponent,我们还要从一个生命周期函数 shouldComponentUpdate 说起,从函数名字我们就能看 ...

  9. ReactJs 的各个版本生命周期、API变化 汇总(一、V16.0.0)

    目录 一.React 各个版本之间的纵向对比 二.React 的基础 1.Components and Props 三.React V 16.0.0 1. The Component Lifecycl ...

随机推荐

  1. C#统计目录中文件MD5值

    1. [代码]统计目录中文件MD5值 using System.IO;using System.Security.Cryptography;using System.Collections;using ...

  2. DBGrid1

    A.ShowMessage(IntToStr(Column.Index));   B.ShowMessage(IntToStr(dbgrid1.SelectedField.Index)); .得到当前 ...

  3. node.js+express+jade系列三:404错误的配置

    1:新建一个404.jade 2:在app.js后面配置如下代码 app.use(function(req, res){        res.render("404", {sta ...

  4. define的用法与注意事项

    ------------------------------------------------- 在编程使用宏替换时,当字符串中不只一个符号时,加上括号表现出优先级, 如果是带参数的宏定义,则要给宏 ...

  5. linux命令学习笔记(50):crontab命令

    前一天学习了 at 命令是针对仅运行一次的任务,循环运行的例行性计划任务,linux系统则是由 cron (crond) 这个系统服务来控制的.Linux 系统上面原本就有非常多的计划性工作,因此这个 ...

  6. 【leetcode刷题笔记】Populating Next Right Pointers in Each Node II

    What if the given tree could be any binary tree? Would your previous solution still work? Note: You ...

  7. 2017-2018-1 20179215《Linux内核原理与分析》第二周作业

    20179215<Linux内核原理与分析>第二周作业 这一周主要了解了计算机是如何工作的,包括现在存储程序计算机的工作模型.X86汇编指令包括几种内存地址的寻址方式和push.pop.c ...

  8. MySQL 和 InnoDB

    发现一篇总结的很不错的文章,转一下 (原文作者:Draveness   原文链接:https://draveness.me/mysql-innodb) 作为一名开发人员,在日常的工作中会难以避免地接触 ...

  9. oracle 12c 新特性之不可见字段

    在Oracle 11g R1中,Oracle以不可见索引和虚拟字段的形式引入了一些不错的增强特性.继承前者并发扬光大,Oracle 12c 中引入了不可见字段思想.在之前的版本中,为了隐藏重要的数据字 ...

  10. Parallel Programming-Task Base

    Parallel.For/ForEach是数据层面的并行,本文所讲的Task是将不同的操作并行执行,本文主要内容: Task的工作模型 初始化Task 完成Task 取消Task 一.Task工作模型 ...