【问题标题】:React - How to make a call to web api to check username is valid?React - 如何调用 web api 来检查用户名是否有效?
【发布时间】:2020-11-06 06:52:45
【问题描述】:

我有一个登录页面(下面的代码),它要求输入用户名登录,我尝试添加检查以确保长度为 7(我的数据库中任何用户的长度)并且只输入数字并且不是字母。但是我现在想调用我的 web api 来检查输入的用户名是否有效,但我不知道该怎么做,有人可以帮忙吗?

在我的 API 中,我有一个 get all usernamers 方法和一个 get user/ 方法

import React, { useState } from "react";
import { useHistory } from "react-router-dom";
import "./Login.css";

export default function LogIn() {
  const history = useHistory();
  const [value, setValue] = useState("");
  const regexp = /^[0-9\b]+$/;
  

  function handleChange(e) {
    setValue(e.target.value);
  }

  function handleSubmit(e) {
    e.preventDefault();
    
    if (!regexp.test(value)) {
      alert("Username should not contain letters, please re-enter");

      return;
    }

    return history.replace("/UserWelcome", value);
  }

  return (
    <div className="Login">
        <form onSubmit={handleSubmit}>
        <h1>Log into our Messaging Service</h1>
          <label>
            Username:
            <input
              type="text"
              name="UserId"
              value={value}
              onChange={handleChange}
              required
              maxLength="7"
              minLength="7"
            />
          </label>
          <button>Log In</button>
        </form>
    </div>
  );
}

【问题讨论】:

  • 你的意思是使用fetch
  • 是的,我不确定它在代码中的哪个位置,在其他地方我在 componentDidMount() 中有它,但我在这个文件中没有它,所以我自己搞糊涂了。以前我使用过 this.setState({ isLoading: true }); const proxyurl = "cors-anywhere.herokuapp.com"; const url = ""; fetch(proxyurl + url) .then(res => res.json()) .then(data => this.setState({ data: data, isLoading: false }));在构造函数中设置数据和加载,但我在这个文件中没有那个,对不起,如果这是一个非常初学者的问题,我是新人
  • 您将代码放在评论中,不再可读,您能否重新编辑您的测验添加代码

标签: reactjs asp.net-core-webapi react-forms


【解决方案1】:
  1. 获取useEffect中的数据

How to make a get request in useEffect

  1. 使用 filter、includes 或 indexOf 方法根据输入值过滤响应数据

  2. 如果为真则验证值

How to use filter method

How to use indexOf

How to use includes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 2014-06-30
    • 1970-01-01
    • 2016-09-30
    相关资源
    最近更新 更多