使用React开发时,某些父组件会不断触发props来更新子组件,如果props频发触发更新,那么用户在输入一些数据时总是会被刷新,会出现频繁失去控件焦点的问题,这个问题的解决方式是将props和state的触发更新的逻辑分开:
/**
* React 16.3.1
* 拆分props 和 state 更新组件逻辑。
* @author dzy
*/
@connect((state)=>{
return state;
})
class TestComponent extends PureComponent {
// 此处省略constructor
state = {
num: 0,
changed: false, // 调用setState时更新为true
shouldUpdate: false, // shouldComponentUpdate中判断是否更新
}
static getDerivedStateFromProps(nextProps, prevState) {
const nextState = {
...prevState,
changed: false,
shouldUpdate: prevState.changed,// 调用setState()时,changed会变为true
};
// 省略其他nextState的处理
return nextState;
}
shouldComponentUpdate(nextProps, nextState, nextContext) {
const isPropsShouldUpdate = (prevProps, nextProps) => {
// 此处写props更新时的逻辑
return prevProps.data !== nextProps.data;
}
const isStateShouldUpdate = (nextState)=> {
return nextState.shouldUpdate;
}
return isPropsShouldUpdate(this.props, nextProps) || isStateShouldUpdate(nextState);
}
/** 重写setState方法,调用此方法时会设置changed字段为true */
setState(state, callback) {
const nextState = {...state, changed: true};
super.setState(state, callback);
}
render() {
console.log("state.num: ", this.state.num, " props.num", this.props.num);
return <button onClick={()=>{
this.setState({num: this.state.num+1});
}}>
Click Me
</button>;
}
}