08.getDeriveStateFromProp案例
案例讲解请观看视频,这里呈现相关代码:
js
import React from './react';
import ReactDOM from './react-dom';
class DerivedState extends React.Component {
constructor(props) {
super(props);
this.state = {prevUserId: 'zhangsanfeng', email: 'zhangsanfeng@xx.com' };
}
// https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops
// 1.在render函数执行之前调用
// 2.返回一个对象则更新state,返回null表示没有任何更新
// 3.使用这个函数的场景很少,当state需要随着props的变化而变化的时候才会用到,其实相当于一种缓冲机制
// 4.如果需要使用的时候,可以考虑用memoization技术
// memoization技术介绍:https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization
// 5.静态函数不能访问类实例,因此多个类组件可以抽取为纯函数的公用逻辑
// 6.该函数在初始化挂载,更新,调用forceUpdate都会执行,与场景无关,而UNSAFE_componentWillReceiveProps只在由于父组件导致的更新的场景下调用,组件内的setState导致的更新不会调用
static getDerivedStateFromProps(props, state) {
// Any time the current user changes,
// Reset any parts of state that are tied to that user.
// In this simple example, that's just the email.
if (props.userId !== state.prevUserId) {
return {
prevUserId: props.userId,
email: (props.userId + '@xx.com')
};
}
return null;
}
render() {
return (
<div>
<h1>Email:</h1>
<h2>{this.state.email}</h2>
</div>
);
}
}
class ParentClass extends React.Component{
constructor(props) {
super(props);
this.state = {id: 'zhangsanfeng'};
}
changUserId = ()=>{
this.setState({
id: 'dongfangbubai'
})
}
render(){
return <div>
<input type='button' value="点击改变UserId" onClick={()=>this.changUserId()}/>
<DerivedState userId={this.state.id}/>
</div>
}
}
ReactDOM.render(<ParentClass />, document.getElementById('root'));