关于javascript:react17中生命周期改变组件挂载流程微调

10次阅读

共计 1624 个字符,预计需要花费 5 分钟才能阅读完成。

react17 的版本更新了,做了一些更新,最近学习了新版的生命周期,来应用比照 16.8 的版本

旧版本:

新版本:

能够看到新版的生命周期中 componentWillMount, componentWillReceiveProps, componentWillUpdate 三个生命周期被干掉了,其实还没被干掉,应用时会报正告:(componentWillReceiveProps 也一样的正告)

为啥举荐加 UNSAFE_ 前缀,官网阐明:新生命周期差别
目标是为了 react18 版本的 异步渲染更新,请移步官网去查看具体:异步渲染更新新个性摸索

新生命周期外面,有两个函数 getDeriveStateFromPropsgetSnapshotBeforeUpdate

getDeriveStateFromProps

从 props 获取一个派生的状态,在调用 render 办法之前调用,函数必须返回一个状态对象或者 null,

// 应用办法,必须加 static!!!static getDerivedStateFromProps(props, state)

如果在 getDerivedStateFromProps 中返回了一个状态对象(跟定义的 state 中一样),视图中的值会被函数返回值拦挡并赋值为以后函数返回的状态对象中的值,并且对 state 内容操作,视图也不会更新(卸载组件还是没影响)。

应用很少

// state 的值追随 props 值变更而变更
// 例如判断 props 内值是奇数还是偶数,来确定用 state 还是用 props
// 官网举例实现 <Transition> 组件很容易,追随信息判断哪些组件做动画
static getDerivedStateFromProps(props, state) {props.xx === xx ? props : state;}

getSnapshotBeforeUpdate

获取更新前的快照,从 DOM 中捕捉一些信息(例如,滚动地位)。此生命周期的任何返回值将作为参数传递给 componentDidUpdate()。应返回 snapshot 的值(或 null

什么是 snapshot??

答案是什么都能够!!!灵便的 js,哈哈哈

联合上述,咱们的 componentDidUpdate() 办法中的参数就应该是 prevProps, prevState

来个例子,滚动地位定位

class NewsList extends React.Component{state = {newsArr:[]}
    componentDidMount(){setInterval(() => {
            // 获取原状态
            const {newsArr} = this.state
            // 模仿一条新闻
            const news = '新闻'+ (newsArr.length+1)
            // 更新状态
            this.setState({newsArr:[news,...newsArr]})
        }, 1000);
    }
    getSnapshotBeforeUpdate(){
        // 返回每一条新闻的高度,就是咱们说的,return this.refs.list.scrollHeight
    }
    componentDidUpdate(prevProps, prevState, height){
        // 计算滚动到以后想显示的条目地位并且放弃不动
        // height 就是咱们说的 snapshot 的值!!!!this.refs.list.scrollTop += this.refs.list.scrollHeight - height
    }
    render(){
        return(
            <div className="list" ref="list">
                {this.state.newsArr.map((n,index)=>{return <div key={index} className="news">{n}</div>
                    })
                }
            </div>
        )
    }
}
ReactDOM.render(<NewsList/>,document.getElementById('test'))
正文完
 0