我想将 AngularJS 登录页面转换为 ReactJS。我编写了代码,但我想知道这是否是正确的方法,以及在我完成之前是否正确。另外我想添加仪表板页面,该页面只能通过身份验证访问,用户登录后将被重定向到仪表板。
$scope.login=function(){
$scope.newuser={
'password':$scope.signinpassword,
'email':$scope.emailid
}
return $http.post('/api/authenticate',$scope.newuser).then(function(response,status){
if(response.data=='redirect'){
$window.location.href="/dashboard";
}else if(response.data=='verifyemail'){
angular.element(document.querySelector('#verifyemailbtn')).click();
}else if(response.data=='Invalid Password'){
window.alert("Incorrect Password");
$scope.error='Failed to authenticate'
}
});
}
到目前为止我翻译的reactjs代码
class Login extends Component {
constructor(props){
super(props);
this.state={
emailid:'',
password:''
}
}
performLogin = async (event) => {
var body={
"emailid":"this.state.emailid",
"password":"this.state.password"
}
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: body
};
const url = "api/login";
try {
const response = await fetch(url, options);
const result = await response.json();
console.log(`login successful`);
} catch (error) {
console.error("login credentials wrong");
}
};
render() {
return (
<div>
<input type="text"
placeholder="emailid"
onChange = {(event,newValue) => this.setState({emailid:newValue})}
/>
<br/>
<input
type="password"
placeholder="Enter your Password"
onChange = {(event,newValue) => this.setState({password:newValue})}
/>
<br/>
<button type="submit" onClick={(event) => this.performLogin(event)}/>
</div>
);
}
}
export default Login;
最佳答案
您的代码接近正常,但存在一些语法问题。
1-您需要为构造函数中的方法绑定(bind)“this”
2-删除performLogin中this.state.emailid的双引号
3-您不需要为每个输入提供许多函数,您只需使用一个函数即可处理所有输入字段,如下所示。
我重构了你的代码:-)
class Login extends Component {
constructor(props){
super(props);
this.performLogin = this.performLogin.bind(this)
this.handleChange = this.handleChange.bind(this)
this.state={
emailid:'',
password:''
}
}
performLogin = async (event) => {
const { enteredText } = this.state;
var body={
"emailid":this.state.emailid,
"password":this.state.password
}
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: body
};
const url = "api/login";
try {
const response = await fetch(url, options);
const result = await response.json();
$window.location.href="/dashboard";
} catch (error) {
console.error("login credentials wrong");
}
};
handleChange(e) {
this.setState({[e.target.name]:e.target.value})
}
render() {
return (
<div>
<input type="text"
placeholder="emailid"
onChange = {handleChange}
/>
<br/>
<input
type="password"
placeholder="Enter your Password"
onChange = {handleChange}
/>
<br/>
<button type="submit" onClick={this.performLogin}/>
</div>
);
}
}
export default Login;
对于重定向,您可以使用像 React-Router 这样的库或者只是将 console.log(login success
) 替换为 $window.location.href="/dashboard"
关于javascript - 在reactjs中验证登录页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59223827/