1.新版去掉了原来的componentWillMount,componentWillUpdate,componentWillReceiveProps。
2.新增函数 getDerivedStateFromProps
-
控制state的值在任何时候都取决于props
-
返回值为null或state对象,不能为undefined
-
原型对象自身静态函数,使用前要加static
static getDerivedStateFromProps(props,state){
console.log('getDerivedStateFromProps',props,state);
return props
}
3.新增函数 getSnapshotBeforeUpdate
- 可接收更新前的props和state,并传递给componentDidUpdate
- 返回值为null或某个值,不能为undefined
- 返回值传递给componentDidUpdate
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(preProps,preState,height){
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'))