a dive in react lifecycle
背景:我在react文档里找生命周期的图,居然没有,不敢相信我是在推特上找到的。。。

正文
react v16.3 新生命周期:
- static getDerivedStateFromProps
- getSnapshotBeforeUpdata
1: getDerivedStateFromProps, 在render之前,返回一个obj更新state,或者null不更新state, 这个生命周期的使用场景是:state根据props变化。
static getDerivedStateFromProps(nextProps: SearchProps, prevState: SearchState) {
const { location } = nextProps
const state = location.state
if (state && (state.keyword !== prevState.keyword)) {
const { keyword } = statereturn {
pageState: 0,
employee: {
hit: 0,
count: 0,
data: [],
currentOffset: 0
},
document: {
hit: 0,
count: 0,
data: [],
currentOffset: 0
},
keyword,
needExact: false
}
}
return null
}
2: getSnapshotBeforeUpdata 触发时间:在实际dom挂载之前,虚拟dom构建之后。返回的任何数据或者null,都将作为componentDidUpdate()的参数。
getSnapshotBeforeUpdate(prevProps, prevState) {
// Are we adding new items to the list?
// Capture the scroll position so we can adjust scroll later.
if (prevProps.list.length < this.props.list.length) {
const list = this.listRef.current;
return list.scrollHeight - list.scrollTop;
}
return null;
}
componentDidUpdate(prevProps, prevState, snapshot) {
// If we have a snapshot value, we've just added new items.
// Adjust scroll so these new items don't push the old ones out of view.
// (snapshot here is the value returned from getSnapshotBeforeUpdate)
if (snapshot !== null) {
const list = this.listRef.current;
list.scrollTop = list.scrollHeight - snapshot;
}
}
建议用法总结请移步:https://juejin.im/post/5aca20c96fb9a028d700e1ce
这里拷贝一个我用到的一种情况:props更新时重新请求
// old
componentWillReceiveProps(nextProps) {
if (nextProps.id !== this.props.id) {
this.setState({externalData: null});
this._loadAsyncData(nextProps.id);
}
} // new
static getDerivedStateFromProps(nextProps, prevState) {
// Store prevId in state so we can compare when props change.
if (nextProps.id !== prevState.prevId) {
return {
externalData: null,
prevId: nextProps.id,
};
}
// No state update necessary
return null;
}
componentDidUpdate(prevProps, prevState) {
if (this.state.externalData === null) {
this._loadAsyncData(this.props.id);
}
}
我的使用:
componentDidUpdate(prevProps: SearchProps, prevState: SearchState) {
const { keyword, needExact } = this.state
if (keyword && (keyword !== prevState.keyword)) { // 上一次的state和这一次的对比,如果需要,就进行fetch数据,并setstate。其中this.state就是getDerivedStateFromProps返回的 更新后的state
if (needExact) {
this._fetchExactData(this.state.keyword)
this.setState({
needExact: false
})
} else {
Promise.all([this._fetchInitData('document'), this._fetchInitData('employee')])
.then(values => {
let pageState = 0
const { state } = this.props.location
if (state && state.type) {
pageState = state.type
} else if (!values[1] && values[0]) {
pageState = 1
}
this.setState({
pageState,
})
})
}
}
}
最后,记录一个小知识点:
由于state变化,需要出发请求数据的,在componentDidUpdate中进行。
a dive in react lifecycle的更多相关文章
- React Lifecycle
React Lifecycle 分为三种: 初始化阶段 状态的更新 销毁 实例化: ReactDom.render 用于将模板转换成HTML语言,并插入DOM节点. 1.getDefaultProps ...
- React LifeCycle API
React LifeCycle API old API & new API 不可以混用 demo https://codesandbox.io/s/react-parent-child-lif ...
- React LifeCycle Methods & re-learning 2019
React LifeCycle Methods & re-learning 2019 v16.9.0 https://reactjs.org/docs/react-component.html ...
- 一图解析 React组件生命周期 (React Component Lifecycle)
React LifeCycle v1 参考官方文档作成 可放大 参考:https://reactjs.org/docs/react-component.html 数字补丁数字补丁数字补丁数字补丁数 ...
- React (Native) Rendering Lifecycle
How Does React Native Work? The idea of writing mobile applications in JavaScript feels a little odd ...
- react与jQuery对比,有空的时候再翻译一下
参考资料:http://reactfordesigners.com/labs/reactjs-introduction-for-people-who-know-just-enough-jquery-t ...
- 如何用 React Native 创建一个iOS APP?(三)
前两部分,<如何用 React Native 创建一个iOS APP?>,<如何用 React Native 创建一个iOS APP (二)?>中,我们分别讲了用 React ...
- 从性能角度看react组件拆分的重要性
React是一个UI层面的库,它采用虚拟DOM技术减少Javascript与真正DOM的交互,提升了前端性能:采用单向数据流机制,父组件通过props将数据传递给子组件,这样让数据流向一目了然.一旦组 ...
- 携程React Native实践
React Native(下文简称 RN)开源已经一年多时间,国内各大互联网公司都在使用,携程也在今年 5 月份投入资源开始引入,并推广给多个业务团队使用,本文将会分享我们遇到的一些问题以及我们的优化 ...
随机推荐
- 微信自用高性能通用key-value组件MMKV已开源!
1.MMKV简介 腾讯微信团队于2018年9月底宣布开源 MMKV ,这是基于 mmap 内存映射的 key-value 组件,底层序列化/反序列化使用 protobuf 实现,主打高性能和稳定性.近 ...
- 第73节:Java中的HTTPServletReauest和HTTPServletResponse
第73节:Java中的HTTPServletReauest和HTTPServletResponse HTTP协议 客户端与服务器端通讯的一种规则. request: 请求行 请求头 请求体 respo ...
- python 将一个列表去重,并且不打乱它原有的排列顺序
old_lst = [2, 2, 1, 1, 3, 4] new_lst = list(set(old_lst)) new_lst.sort(key=old_lst.index) print(new_ ...
- VIM -小技巧汇总
一 代码自动对齐: 1 命令行模式下先输入gg 然后按=后输入大写的G,这样整个文件的代码就对齐了. 二 选中多行缩进 1.按v进入visual状态,选择多行,用>或<缩进或缩出 2. 通 ...
- js代码跑马灯效果-----轮播图字效果!
文字元素: <p id="yc-msg">你有本事来打我呀!</p> js执行代码: function ycMsg() { // 获取 标签 var pOb ...
- tensorflow笔记4:函数:tf.assign()、tf.assign_add()、tf.identity()、tf.control_dependencies()
函数原型: tf.assign(ref, value, validate_shape=None, use_locking=None, name=None) Defined in tensorflo ...
- HTML5拍照、摄像机功能实战
HTML5拍照.摄像机功能实战 苏格团队 作者:Tomey 开篇 最近在做一个chrome app的云相机应用,应用包括拍照.摄像.保存照片视频.上传文件等等核心功能,其中涉及到很多HTML5对媒体流 ...
- 2.Git基础-仓库的获取方式与Git文件的状态变化周期(生命周期)
1.仓库的获取 Git仓库的获取有两种方式: 1.从现有目录或者是项目中导入所有文件到Git中. 2.从一个服务器clone一个现有的Git仓库. 如果使用第一种方式,只需要在你希望被Git进行管理的 ...
- 对requestAnimationFrame的一点理解
假设一个web页面为60fps(fps意为frame per second),这意为着这个页面每秒钟能重新渲染60次,60帧/1000ms换算过来约为16.6ms/帧. requestAnimatio ...
- Apache-Flink深度解析-TableAPI
您可能感兴趣的文章合集: Flink入门 Flink DataSet&DataSteam API Flink集群部署 Flink重启策略 Flink分布式缓存 Flink重启策略 Flink中 ...