我是React的初学者,正在实现一个函数,在该按钮上单击render方法,然后转到foo函数。在该功能中,我将用户名和密码发送到服务器。
如果用户名和密码正确,它将返回一个JSON对象,例如
{"Result":1,"Cookie":"COOKIE!!!"}
现在,如果结果为0,我想打印一条错误消息,指出用户名和密码无效,如果正确,我想将其重定向到其他组件类。有人可以帮我吗?
我尝试阅读很多文章,但无法做到。问题是,我想在网页上打印某些内容,但这只能在渲染中完成。当我获得Cookie时,我在函数foo中,所以我不知道如何打印错误消息。
我也不知道如何在成功通过身份验证后将其带到新页面,即cookie为1
import React from 'react';
import './style.scss';
import LoginImage from './LoginImage.png'
import Button from 'react-bootstrap/Button'
import Form from 'react-bootstrap/Form'
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom'
//import Logfailed from './Logfailed'
import Flood from './Flood'
class UserLogin extends React.Component {
constructor(props) {
super(props);
this.state = {userName:'', password:'', act:'l', flag:0};
this.handleChange1 = this.handleChange1.bind(this);
this.handleChange2 = this.handleChange2.bind(this);
this.handleClick = this.handleClick.bind(this);
}
async handleClick(e) {
const url = 'http://52.8.557.164/user'
const data = {username:this.state.userName, password:this.state.password, action:this.state.act};
try {
const response = await fetch(url,
{
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
},
});
const json = await response.json();
if(json['Result'] === 1) {
this.state.flag=1;
}
else {
this.state.flag=2;
}
console.log('Success', JSON.stringify(json));
console.log(json['Cookie']);
} catch (error) {
console.error('Error', error);
}
}
handleChange1(e) {
this.setState({userName: e.target.value})
}
handleChange2(e) {
this.setState({password: e.target.value})
}
render() {
const err = this.state.flag;
return (
<div className = 'outer-container' ref={this.props.containerRef}>
<div className = 'header'> Login </div>
<div className="content">
<div className="image">
<img src={LoginImage} />
</div>
<Form className = 'form'>
<Form.Group controlId="formBasicEmail" className = 'form-group'>
<Form.Label style={{marginTop: '90px'}}>Username</Form.Label>
<Form.Text className="text-muted" htmlFor="username"></Form.Text>
<input type="text" value = {this.state.userName} name="username" placeholder="username" onChange={this.handleChange1}/>
</Form.Group>
<Form.Group controlId="formBasicPassword" className = 'form-group'>
<Form.Label>Password</Form.Label>
<Form.Text className="text-muted" htmlFor="password"></Form.Text>
<input type="password" value = {this.state.password} name="password" placeholder="password" onChange={this.handleChange2} />
</Form.Group>
</Form>
</div>
<div className="footer">
<Button variant="outline-primary" size="lg" onClick={this.handleClick} className="btn" block>
Login
</Button>
</div>
</div>
);
}
}
export default UserLogin;
首先,在您的handleClick()方法中,您尝试直接修改组件的状态,而不是使用React的内置setState()方法。这将阻止您的UI对更新做出反应,因为React无法知道组件的状态已更改。
if(json['Result'] === 1) {
this.state.flag=1;
} else {
this.state.flag=2;
}
相反,如果您将代码替换为:
if(json['Result'] === 1) {
this.setState({flag: 1});
} else {
this.setState({flag: 2});
}
然后,这将导致您的组件在每次状态更改时都重新呈现,因此您的应用程序将变得被动。
接下来,如果要在flag属性等于2时向用户显示警告消息,只需在JSX中添加条件表达式。
{ this.state.flag === 2 && <p>Your login credentials could not be verified, please try again.</p>}
这意味着<p>
标签仅在表达式的第一部分即this.state.flag === 2
评估为true时才被评估(因此将被渲染。)>
如果您希望在成功登录后将用户重定向到其他路由,只需从Redirect
导入react-router-dom
组件,并使用以下内容替换render()方法中的return语句:
if (this.state.flag === 1) { return <Redirect to='/route' /> } // else return ( <div className = 'outer-container' ref={this.props.containerRef}> // ... add the rest of your JSX )
有关此解决方案的更多信息,请参见this link。
因此,最终,您的render()方法可能类似于以下内容:
render() { if (this.state.flag === 1) { return <Redirect to='/route' /> } // else return ( <div className = 'outer-container' ref={this.props.containerRef}> <div className = 'header'> Login </div> <div className="content"> <div className="image"> <img src={LoginImage} /> </div> { this.state.flag === 2 && <p>Your login credentials could not be verified, please try again.</p>} // ... add the rest of your JSX ) }
~~~更新~~~
如果<Redirect>
方法不起作用,我们也可以尝试另一种方法(也有详细的here)。假设我们从API返回了正确的标志,那么在您的提取请求得到解析后,我们可以以编程方式重定向用户。因此,您可以尝试:
if(json['Result'] === 1) { this.setState({ flag: 1 }); this.props.history.push('/route') }
但是,为了使用这种方法,您还需要在export语句中使用
withRouter
HOF包装组件。因此,代替:
export default MyComponent
您将需要做:
export default withRouter(MyComponent)
只需确保从
withRouter
导入react-router-dom
。