我正在尝试使用react create构建一个登录表单,它使用以下json API中的用户名和密码值:https://api.myjson.com/bins/fyufr
代码:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './Login.css';
class Login extends Component {
constructor() {
super();
this.state = {
data: [],
userName: "",
password: "",
token: "",
};
} //end constructor
change = (e) => {
this.setState({
[e.target.name]: e.target.value
});
}; //end change
onSubmit = (e) =>{
e.preventDefault();
console.log(this.state);
this.setState({
userName: "",
password: "",
token: "",
});
var userName = document.getElementById('userName').value
var password = document.getElementById('password').value
for(var i=0; i < this.state.data.length; i++) {
if(userName == this.state.data[i].userName && password == this.state.data[i].password){
console.log(userName + "is logged in")
}
}
console.log("incorrect username or password")
};
componentWillMount() {
fetch('https://api.myjson.com/bins/fyufr', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json',
},
/*body: JSON.stringify({
username: '{userName}',
password: '{password}'
})*/
}) /*end fetch */
.then(results => results.json())
.then(data => this.setState({ data: data })
)
} //end life cycle
render() {
console.log(this.state.data);
return (
<form>
<input
name="userName"
placeholder="User Name"
value={this.state.userName}
onChange={e => this.change(e) }
/>
<input
name="password"
type="password"
placeholder="Password"
value={this.state.password}
onChange={e => this.change(e) }
/>
<input
name="token"
placeholder="Token"
value={this.state.token}
onChange={e => this.change(e) }
/>
<button onClick={e => this.onSubmit(e)}>Submit</button>
</form>
);
}
}
export default Login;
我的代码在以下行中出错:var userName = document.getElementById('userName') . value
... this.state.data的值向控制台输出json文件中的值,但是当单击提交按钮时,我得到上面提到的错误 . 我的目标是在输入匹配的用户名和密码时让登录表单将用户引导到登录页面,但首先,我正在尝试解决遇到的错误 . 我是React JS的新手,我能不能得到一些关于我做错的指导?
2 回答
简单的修复 . 您在表单输入上缺少
id
. 你试图得到document.getElementById('userName').value
,它返回null
,因为它不存在 .以下是您的代码的工作示例:https://stackblitz.com/edit/react-m7iwpt
你没有设置我的输入...