【问题标题】:How to push history to a specific component by using async fetch in react js如何通过在 react js 中使用异步获取将历史推送到特定组件
【发布时间】:2020-05-13 23:43:06
【问题描述】:

我正在使用 reactjs 编写一个登录页面,我在一个单独的烧瓶应用程序中生成我的 OTP。我在单击按钮时调用一个函数,该函数获取 API 并检查 OTP 是否匹配。它在后端提供正确的日志值,但在前端,即使 OTP 无效,它也会将历史记录推送到应该保​​留在同一页面上的下一页。 我的代码有什么问题以及如何解决? 我的前端代码如下:

import React, { Component } from "react";
import "../pod.css";
export default class OTPVerify extends Component {
  constructor(props) {
    super(props);
    //const { params } = this.props.location.state;
    //var data = this.props.location.userPhone;

    console.log(this.props.history.location.state.userPhone);
    this.state = {
      userPhone: this.props.history.location.state.userPhone,
      userotp: "",
      verified: false,
      isMounted: false,
      existingUser: false
    };
    this.handleChange = this.handleChange.bind(this);
  }
  componentDidMount() {
    this.setState(
      {
        isMounted: true
      },
      function() {}
    );
  }

  handleChange(event) {
    //console.log(event.target.value);
    const name = event.target.name;
    const value = event.target.value;

    this.setState({ [name]: value });
  }

  verifyOTP = event => {
    if (this.state.isMounted == true) {
      console.log("XXX");
      if (this.isOTPValid(this.state.userotp)) {
        this.forwardToHomePage();
      } else {
        alert("please enter a valid OTP");
        event.preventDefault();
      }
    }
    //
  };
  async isOTPValid(phone) {
    if (phone.length === 6) {
      var val = this.checkOTP();
      console.log(val);
      return val;
      //console.log(this.state.verified);
    } else {
      return false;
    }
  }

  async checkOTP() {
    await fetch("http://192.168.43.212:5000/api/verifyOTP", {
      method: "POST",
      credentials: "include",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        pod_Otp: this.state.userotp,
        userPhone: this.state.userPhone
      })
    })
      .then(response => response.json())
      .then(responseJson => {
        this.setState(
          {
            verified: responseJson.validOTP,
            existingUser: responseJson.clientExists
          },
          function() {
            console.log(this.state.verified);
            console.log(this.state.existingUser);
          }
        );
        return this.state.verified;
      })
      .catch(error => {
        console.log(error);
      });
  }
  forwardToHomePage() {
    if (this.state.existingUser) {
      this.props.history.push("/Home", { userPhone: this.state.userPhone });
    } else {
      this.props.history.push("/customerProfile", {
        userPhone: this.state.userPhone,
        edit_enabled: true
      });
    }
  }
  render() {
    return (
      <div className="login-form">
        <form method="post">
          <h2 className="text-center">Sign in</h2>

          <img
            src="cinqueterre.jpg"
            className="rounded-circle"
            alt="Book Pandit"
          />

          <div className="or-seperator">
            <i>or</i>
          </div>
          <div className="form-group">
            <div className="input-group">
              <span className="input-group-addon">
                <i className="fa fa-user"></i>
              </span>
              <input
                type="text"
                className="form-control"
                name="userotp"
                required="required"
                onChange={this.handleChange}
              ></input>
            </div>
          </div>

          <div className="form-group">
            <button
              type="submit"
              className="btn btn-success btn-block login-btn"
              onClick={this.verifyOTP}
            >
              Verify OTP
            </button>
          </div>
        </form>
      </div>
    );
  }
}

【问题讨论】:

  • 当我在无效 otp 上检查控制台时,最初它显示承诺待处理
  • responseJson.clientExists 的值是多少?如果它是真的,那么这个检查if (this.state.existingUser) 将评估为true。 IE。如果您的 JSON 响应类似于 {"existingUser": "false"},则非空字符串是真实的。
  • 我的 Json 响应是我想要的方式,但即使不检查值也会发生重定向
  • 抱歉,之前在移动设备上浏览,专注于我看到的导航推送。后来意识到forwardToHomePage 在两个分支中都进行了推送,但您没想到它们会这样做。添加了答案。

标签: reactjs promise async-await fetch


【解决方案1】:

isOTPValid 是一个异步函数,checkOTP 也是如此。 checkOTP 正确地等待获取响应,但 isOTPValid 没有。在verifyOTP 中,您正在检查isOTPValid 的当前返回值,因为没有等待,所以它是未决的承诺。您需要等待 checkOTP 返回的隐式承诺的解决。

verifyOTP = event => {
  if (this.state.isMounted == true) {
    console.log("XXX");
    if (this.isOTPValid(this.state.userotp)) {
      this.forwardToHomePage();
    } else {
      alert("please enter a valid OTP");
      event.preventDefault();
    }
  }
};

async isOTPValid(phone) {
  if (phone.length === 6) {
    var val = await this.checkOTP(); // this is a promise!!! you should await its resolution
    console.log(val);
    return val;
    //console.log(this.state.verified);
  } else {
    return false;
  }
}

【讨论】:

    猜你喜欢
    • 2020-10-16
    • 2017-07-30
    • 1970-01-01
    • 2020-08-30
    • 2022-07-18
    相关资源
    最近更新 更多