React.js,超时-几秒钟后如何隐藏div

时间:2020-10-19 15:15:14

标签: reactjs forms timeout

我正在使用react.js制作表单。我正在尝试使div出现,然后在提交表单后消失。我该如何正确地做到这一点?

提交表单后,我的代码目前仅将我带到空白页。

根据要求更新

#!/bin/bash

# https://gist.github.com/fntlnz/cf14feb5a46b2eda428e000157447309

openssl genrsa -des3 -out rootCA.key 4096

openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.crt

1 个答案:

答案 0 :(得分:1)

React的this.setState的第二个参数是回调函数,而不是静态值。您可能打算用回调来调用setTimeout来更新状态。我还建议将您的函数的名称更改为更有意义的名称,例如resetMessage,以免模糊不清。然后,为了完善起见,您应该保存计时器ref并在组件卸载时将其清除,以免尝试设置已卸载组件的状态。

constructor(props) {
  super(props)
  this.state = {
    messageConfirm: '',
  };
  this.timerId = null;
}

resetMessage() {
  this.timerId = setTimeout(() => {
    this.setState({ messageConfirm: "" });
     this.timerId = null;
  }, 5000);
}

submitForm(e) {
  e.preventDefault();
  const isValid = this.validateForm();

  if (isValid) {
    this.confirmEmailMessage();
    this.resetMessage();
    e.target.reset();
    this.resetForm();
  }
}

...

componentWillUnmount() {
  cleatTimeout(this.timerId);
}