【问题标题】:How to find display error message from API in reactjs如何在 reactjs 中从 API 中查找显示错误消息
【发布时间】:2020-09-10 15:33:52
【问题描述】:

我是 React.JS 的新手,正在为联系人创建应用程序。通过 API 验证联系人的字段,如果存在相同的姓名或电话号码,则会在 API 中显示错误消息。我的查询是如何在输入相同姓名或电话号码时在 UI 中显示错误消息。我需要从 Contact API 获取吗?如果是,我可以在DIdmount 中获取联系人的 API,但不知道如何显示错误?任何人都可以帮助我吗?

【问题讨论】:

  • 不建议在装载时获取,这需要比您需要的更多的数据。如果您想实时执行此操作,请在他们完成姓名/号码字段时进行 api 调用以“验证”

标签: reactjs


【解决方案1】:

为错误创建一个状态变量,初始值设置为 "" 或 null。进行 api 调用,服务器(假设您也在构建服务器)应该检查姓名和电话号码是否已经存在。如果它们已经存在,服务器应该返回一个错误。在您的反应应用程序中,在您的 API 调用后捕获错误并将其分配给您的状态变量以防出错。这是客户端使用钩子的示例。

export default function RegistrationForm(props) {
    const [error, setError] = useState(null)
    const errorDiv = error 
        ? <div className="error">
            <i class="material-icons error-icon">error_outline</i>
            {error}
          </div> 
        : '';

    const handleSubmit = e => {
        e.preventDefault();
        setError(null);
        
        const { full_name, user_name, password } = e.target;

        AuthApiService.postUser({
            full_name: full_name.value, 
            user_name: user_name.value, 
            password: password.value
        })
            .then(user => {
                full_name.value = '';
                user_name.value = '';
                password.value = '';
                props.onRegistrationSuccess();
            })
            .catch(res => {
                setError(res.error);
            })
    };

    return(
        <form className='RegistrationForm'
            onSubmit={handleSubmit}
        >  
            <div className='full_name'>
                <label htmlFor='RegistrationForm__full_name'>
                    Full name
                </label>
                <Input
                    name='full_name'
                    type='text'
                    required
                    id='RegistrationForm__full_name'>
                </Input>
            </div>
            <div className='user_name'>
                <label htmlFor='RegistrationForm__user_name'>
                    User name
                </label>
                <Input
                    name='user_name'
                    type='text'
                    required
                    id='RegistrationForm__user_name'>
                </Input>
            </div>
            <div className='password'>
                <label htmlFor='RegistrationForm__password'>
                    Password
                </label>
                <Input
                    name='password'
                    type='password'
                    required
                    id='RegistrationForm__password'
                    >
                </Input>
            </div>
            <div className='confirm-password'>
                <label htmlFor="LoginForm__confirm-password">
                    Retype Password
                </label>
                <Input
                    name='confirm-password'
                    type="password"
                    required
                    id="LoginForm__confirm-password">
                </Input>
            </div>
            {errorDiv}
            <Button type='submit' variant='contained' color='default'>
                Register
            </Button>
        </form>
    )
}

【讨论】:

    【解决方案2】:

    是的,如果您想从 api 响应中获得确切的错误消息,则可以通过 .then(responseJson=&gt; { console.log(responseJson.response.data.message) })

    【讨论】:

      【解决方案3】:

      有一个 API 来检查名称是否可用,并在用户更改输入内容时点击 API。

      import React, { useState } from "react";
      import ReactDOM from "react-dom";
      
      let delayTimer;
      
      function App() {
        const [name, setName] = useState("");
        const [nameAvailable, setNameAvailable] = useState(null);
      
        async function checkNameAvailable() {
          try {
            const response = await APIUtility.isNameAvailable(name);
      
            const { data = null } = response;
            if (data) {
              setNameAvailable(data); // data may be true or false
            }
          } catch (error) {
            setNameAvailable(null);
          }
        }
      
        function handleNameChange(e) {
          setName(e.target.value);
          if (name.length > 0) {
            if (delayTimer) clearTimeout(delayTimer);
            delayTimer = setTimeout(function() {
              checkNameAvailable();
            }, 1000); // Will do the ajax stuff after 1000 ms, or 1 s
          }
        }
      
        return (
          <form>
            <label htmlFor="invite_code">Enter your name:</label>
            <input
              value={name}
              onChange={handleNameChange}
              type="text"
              name="inviteCode"
              id="invite_code"
              autoComplete="off"
            />
            {nameAvailable && <span>Name already taken</span>}
          </form>
        );
      }
      
      const rootElement = document.getElementById("root");
      ReactDOM.render(<App />, rootElement);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-26
        • 1970-01-01
        • 2020-12-30
        • 2017-01-02
        • 2013-02-05
        • 2011-06-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多