【问题标题】:TypeError: Failed to fetch with input textTypeError:无法获取输入文本
【发布时间】:2018-09-21 05:15:09
【问题描述】:

我在 React 中使用下面的 JS 代码来获取用户名和密码。

当我将用户名的输入类型用作 text 时,我得到“TypeError: Failed to fetch”,但如果我将类型切换为 email,那么 fetch 工作正常。

这是为什么呢?我不希望输入类型为电子邮件,因为它会在提交表单时提示我进行其他检查,例如 @ 符号。

我的 JS:

login() {
  const userObject = {
    username: document.getElementById('inputUsername').value || null,
    password: document.getElementById('inputPassword').value || null
  };
  this.connect('someurl.com', userObject);
}

async connect(url, userObject) {
  try {
    let response = await fetch((url), {
      method: "PUT",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(userObject)
    });
  } catch (e) {
    console.error(e);
  }
}

我的 HTML 输入:

<input type="text" id="inputUsername" />

【问题讨论】:

  • 你从哪里得到这个错误?另外,你能在 sn-p 中创建工作示例吗?
  • 我在浏览器上记录了它,当我使用它时它可以工作:<input type="email" id="inputUsername" />
  • 请创建相同的演示。

标签: javascript html reactjs


【解决方案1】:

当您使用 React 时,您必须始终将输入的值保存在 State 中,并在 ajax 调用中发送 State 值

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      userName: null,
      password: null
    }
    this.UserNameChange = this.UserNameChange.bind(this);
    this.PasswordChange = this.PasswordChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  UserNameChange(event) {
    this.setState({
      userName: event.target.value
    });
  }
  PasswordChange(event) {
    this.setState({
      password: event.target.value
    });
  }
  handleSubmit(event) {
    alert('UserName: ' + this.state.userName + ' and Password: ' + this.state.password);
    event.preventDefault();
  }
  render() {
    return ( 
    <div>
      <form onSubmit = {this.handleSubmit}>
      <input type = 'text' onChange = {this.UserNameChange} placeholder = 'UserName' / >
      <br/>
      <input type = 'text' onChange = {this.PasswordChange} placeholder = 'Password' / >
      <br/>
      <input type = "submit" value = "Submit"/>
      </form> 
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render( <App/> , rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='root' />

【讨论】:

  • 这有帮助,我已将代码更改为使用状态值,但是如果我使用 &lt;input type="text"/&gt;,问题仍然存在
猜你喜欢
  • 1970-01-01
  • 2021-01-24
  • 2017-02-27
  • 2019-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
相关资源
最近更新 更多