【问题标题】:Calling multiple handler methods in react js onSubmit在反应js onSubmit中调用多个处理程序方法
【发布时间】:2022-02-09 00:21:42
【问题描述】:

我正在开发一个使用带有 onSubmit 的搜索表单组件的 React JS 项目。我想调用多个搜索处理程序方法,使 Axios 同时调用多个后端 API。我正在使用一个类组件,我的 onSubmit 调用了一个 searchHandler 方法,该方法包含对后端的多个 axios 调用。但是当我提交表单时出现错误:frontend error

这是我的 onSubmit 调用的搜索处理函数,它包含两个 Axios 调用:

applicationSearchHandler(event) {
    event.preventDefault();

    console.log(this.state.number, this.state.orgChoice);

    LoanAppDataService.getPromoCodeExpiryInfo(
      this.state.orgChoice,
      this.state.promoCode,
      this.state.number
    )
      .then((response) => {
        if (response && response.data && response.data.length > 0) {
          console.log(response.data[0].applicationId);

          this.setState((state) => ({
            ...this.state,
            expiryStatusMessage: response.data[0].message,
            isSearched: true,
            error: false,
          }));
        }
      })
      .catch((error) => {
        this.setState({
          error: !this.state.error,
          errorAlert: "",
          isSearched: false,
        });
      });

    LoanAppDataService.getCorrectPromoCodeInfoEmailAndOrgId(
      this.state.emailId,
      this.state.orgChoice
    )
      .then((response) => {
        this.setState((state) => ({
          associatedPromoMessage: response.data[0].message,
          isSearched: true,
          error: false,
        }));
      })
      .catch((error) => {
        this.setState({
          error: !this.state.error,
          errorAlert: "",
          isSearched: false,
        });
      });

    this.setState((state) => ({
      ...this.state,
      number: "",
      customerName: "",
      orgChoice: "",
    }));

    const isValid = this.validateSsn();
  }

这就是我的 onSubmit 的样子:

<form onSubmit={this.applicationSearchHandler}>

我不完全知道如何纠正这个错误,我尝试了多种方法,但目前似乎没有任何效果。

【问题讨论】:

    标签: javascript html reactjs axios


    【解决方案1】:

    在这部分代码中出现错误

    expiryStatusMessage: response.data[0].message

    最有可能 response.data[0] 为 null 或未定义,这段代码试图从 null 中查找消息,所以它给出了错误

    你可以像这样在这里使用 nullish 运算符

    expiryStatusMessage: response.data[0]?.message

    【讨论】:

    • 我这样做了,但是当我从后端接收信息时,我的状态值没有更新,它仍然未定义。另外,我在这部分代码中遇到错误:i.stack.imgur.com/3fWdc.png
    • 如果 response.data[0] 为 null,则无法获取消息。 Nullish 运算符可能不适用于每个浏览器和版本。你可以试试 response.data[0]==undefined 吗? null(或此状态的默认值):response.data[0].message
    • 我试过了,但没用。每次我这样做时,我的应用都会崩溃
    猜你喜欢
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 2023-03-06
    • 1970-01-01
    • 2020-11-05
    相关资源
    最近更新 更多