componentDidUpdate有两个参数prevProps和prevState,不管是父组件props的修改还是state状态的更改都会触发该方法,而componentWillReceiveProps只有在父组件重新render props改变的时候才会触发。下面的代码是只有上一次的changeForm不包含1且本次props.changeForm包含1才会执行componnetDidUpdate
componentDidUpdate(prevProps: Readonly<FeatureProps>, prevState: Readonly<FeatureState>): void {
const {changeType, ability, changeForm} = this.props;
const isDeligentCustomerShow = changeType === 1
&& !prevProps.changeForm.indexOf('1') > -1 && changeForm.indexOf('1') > -1;
{
this.getDeligentCustomerStatus();
}
return isDeligentCustomerShow;
}
这段代码是只有prevProps.agentId与本次props.agentId不一样时,才会调用componentDidUpdate方法。
componentDidMount(): void {
this.clipboard = new Clipboard('#copyBtn');
this.clipboard.on('success', e => {
console.log('内容已经复制到剪切板啦');
e.clearSelection();
});
this.clipboard.on('error', e => {
console.error('无法复制', e.action);
console.error('Trigger:', e.trigger);
});
}
componentDidUpdate(prevProps: Readonly<FeatureProps>, prevState: Readonly<FeatureState>): void {
if (prevProps.agentId !== this.props.agentId) {
this.clipboard = new Clipboard('#copyBtn');
this.clipboard.on('success', e => {
console.log('内容已经复制到剪切板啦');
e.clearSelection();
});
this.clipboard.on('error', e => {
console.error('无法复制', e.action);
console.error('Trigger:', e.trigger);
});
}
}
componentWillReceiveProps在props发生改变时会执行,在初始化render时并不会执行。在做项目时遇到一个问题:renderSearch方法仅仅在第一次执行了,其后都没有执行。于是加上了componentWillReceiveProps方法。
componentDidMount(): void {
this.context.methods.searchMember(this.handleChange, this.props.value);
}
componentWillReceiveProps(nextProps, nextState) {
if (nextProps.value !== nextState.value) {
this.context.methods.searchMember(this.handleChange, nextProps.value);
}
}