首页 > 解决方案 > componentDidUpdate 中的触发事件

问题描述

我有以下代码:

handleValidate = (value: string, e: React.ChangeEvent<HTMLTextAreaElement>) => {
const { onValueChange } = this.props;
const errorMessage = this.validateJsonSchema(value);

if (errorMessage == null) {
  // it is sure that JsonInputRef.current exists
  this.JsonInputRef.current!.setCustomValidity('');

  onValueChange && onValueChange(value, e);
} else {
  if (this.JsonInputRef.current) {
    this.JsonInputRef.current.setCustomValidity(errorMessage);
  }
}
}

componentDidUpdate(prevProps: JsonInputProps) {
  if (prevProps.value !== this.props.value) {
    this.validateJsonSchema(this.props.value || '');
  }
}

触发事件是一种好习惯,componentDidMount还是更好地实施它setTimeout

标签: javascriptreactjstypescriptevents

解决方案


是的,这也是一个做网络请求的好地方,只要你将当前的 props 与以前的 props 进行比较。

可以立即调用 setState()componentDidUpdate()但请注意它必须包含在条件中。

注意:如果返回 false
componentDidUpdate()将不会被调用 。shouldComponentUpdate()

阅读有关componentDidUpdate()的更多信息。


推荐阅读