【问题标题】:React API Sends Blank Value (Some State Issue)React API 发送空白值(某些状态问题)
【发布时间】:2021-07-13 00:22:07
【问题描述】:

我有一个带有 Validate() 函数的登录表单。我正在尝试将输入值发送到我的 Django 后端,但我收到如下响应。我认为问题在于我正在存储我的数据,例如“input:{}”,但在 App.js 上我有用户名和密码值。我是 React 的新手,我会吓坏的。我需要这个验证功能。我很困惑。

{
    "username": [
        "This field may not be blank."
    ],
    "password": [
        "This field may not be blank."
    ]

LoginForm.js(handle_login 是我的 App.js 上的一个函数)

import React from 'react';
import PropTypes from 'prop-types';


class LoginForm extends React.Component {

  constructor() {
    super();
    this.state = {
      input: {},
      iderr: false,
      data: null,
      errors: {}
    };
     
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }


         
  checkgiris = (e, data) => {
    e.preventDefault();
    fetch('http://localhost:8000/token-auth/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
      })  
      .then(respons => {
        if(respons.status === 200){
         this.props.handle_login(e, this.state.input) 
      }
      else {
        this.setState({iderr:true})
       }
    })
    
  };

  handleChange(e) {
    let input = this.state.input;
    input[e.target.name] = e.target.value;
  
    this.setState({
      input
    });
  }

 

  handleSubmit(e) {
    e.preventDefault();
  
    if(this.validate()){
        console.log(this.state);
        let input = {};
        input["username"] = "";
        input["password"] = "";
        this.setState({input:input});
        this.checkgiris(e, this.state.input) 
    }
  }

  validate(){
    
    let input = this.state.input;
    let errors = {};
    let isValid = true;



    if (!input["username"]) {
      isValid = false;
      errors["username"] = "Username may not blank";
    }


    if (!input["password"]) {
      isValid = false;
      errors["password"] = "Password may not blank";
    }


    this.setState({
      errors: errors
    });

    return isValid;
}

  render() {
    return (
     
      <form onSubmit={this.handleSubmit}>
        <center><h4>Login</h4></center>
        <div class="girisformu">
        <input
          class="girisid"
          id="username"
          type="text"
          placeholder="Username"
          name="username"
          value={this.state.input.username}
          onChange={this.handleChange}
        />
         <div className="text-danger">{this.state.errors.username}</div>
        <input
          class="girispw"
          id="password"
          type="password"
          placeholder="Password"
          name="password"
          value={this.state.input.password}
          onChange={this.handleChange}
        />
         <div className="text-danger">{this.state.errors.password}</div>
         { this.state.iderr ? <div className="text-danger">Your username or password is invalid.</div> : null }
                <br/>
        <input class="girisyapbuton" type="submit" value="Login" />

        </div>
      </form>
    
      
    );
  }
}

export default LoginForm;

LoginForm.propTypes = {
  handle_login: PropTypes.func.isRequired
};

App.js(我没有分享不必要的代码)

function App() {

  const [displayed_form,setDisplayed_form] = useState('');
  const [username,setUsername] = useState('');
  const [logged_in,setLogged_in] = useState(localStorage.getItem('token') ? true : false);

  useEffect(()=>{
    if (logged_in) {
      fetch('http://localhost:8000/api/current_user/', {
        headers: {
          Authorization: `JWT ${localStorage.getItem('token')}`
        }
      })
        .then(res => res.json())
        .then(json => {
          setUsername(json.username);
        });
    }
  },[]) //notice the empty array here


  const handle_login = (e, data) => {
    e.preventDefault();
    fetch('http://localhost:8000/token-auth/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    })
      .then(res => res.json())
      .then(json => {
        localStorage.setItem('token', json.token);
        setLogged_in(true);
        setDisplayed_form('');
        setUsername(json.user.username);
      })
      .catch(error => {
        console.log(error)
      })
  };

  

  const handle_signup = (e, data) => {
  
    e.preventDefault();
    fetch('http://localhost:8000/api/users/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    })
      .then(res => res.json())
      .then(json => {
        localStorage.setItem('token', json.token);
        setLogged_in(true);
        setDisplayed_form('');
        setUsername(json.username);
      });

  };

  const handle_logout = () => {
    localStorage.removeItem('token');
    setLogged_in(false);
    setUsername('');
  };

  const display_form = form => {
    setDisplayed_form(form);
  };



  let form;
  switch (displayed_form) {
    case 'login':
      form = <div class="giris"><LoginForm handle_login={handle_login} /></div>;
      break;
    case 'signup':
      form = <div class="kayitol"><SignupForm handle_signup={handle_signup} /></div>;
      break;
    default:
      form = null;
  }

return(
<div className="App">
<div>
bla bla bla .......

【问题讨论】:

    标签: reactjs django api jwt fetch


    【解决方案1】:

    我已经删除了这些行

    console.log(this.state);
    let input = {};
    input["username"] = "";
    input["password"] = "";
    this.setState({input:input});
    

    现在没事了!

    【讨论】:

      【解决方案2】:

      您在调用checkgiris 函数之前重置输入值。我建议您在 API 调用响应或调用 checkgiris 后重置值:

      if(this.validate()){
        this.checkgiris(e, this.state.input);
        //--> reset input values after this
      }
      

      【讨论】:

      • 我试过但没用 :( 此外,当我尝试随机用户名和密码时,它返回 "{"non_field_errors":["Unable to log in with provided credentials."]}" 作为响应. 但是当我尝试正确的用户名和密码时,它返回““此字段可能不是空白。”错误。
      • 您是否检查了浏览器中的请求正文是否包含您希望发送的数据?如果答案是肯定的,您应该检查后端。
      猜你喜欢
      • 1970-01-01
      • 2021-11-07
      • 2021-10-24
      • 2016-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-01
      相关资源
      最近更新 更多