【发布时间】:2020-11-07 20:44:44
【问题描述】:
我正在开发登录模块。我将 nodeJs 用于我的后端服务。
问题:我想在登录时出现任何错误时显示一条消息。
为此,我会在每次来自服务器的登录请求时向客户端发送一条消息。
- 当客户端用户名和密码正确时,服务器发送“OK”。
2.当密码错误时,服务器发送“密码不匹配!”。
- 当电子邮件不正确时,服务器会发送“用户不在数据库中”。
反应代码:
状态
this.state={
email:'',
password:'',
msg:''
}
我有一个 Login 组件,它呈现所有输入控件和按钮。在登录组件中,我有一个提交按钮,Email 和 Password 的输入控件。
当用户点击提交按钮时,我正在向服务器发出请求。
登录请求:
axios.post('http://localhost:4000/signin',{
email:this.state.email,
password:this.state.password
})
.then(response=>{
if(response.data.msg==='OK'){
window.location.href='/';
}else{
this.setState({
msg:response.data.msg
})
//alert(response.data.msg);
}
})
.catch(err=>console.log(err));
服务器的一切都很好。每次登录失败时,我都会从服务器收到消息。
我正在渲染一个 Message (<Message show={true} msg={this.state.msg}/>) 组件并将 show={true} 和 msg={this.state.msg} 作为道具传递。
消息组件
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import Alert from 'react-bootstrap/Alert';
export default class Message extends React.Component{
constructor(props){
super(props);
this.state={
show:false
}
}
componentDidMount(){
this.setState({show:this.props.show})
}
handleClose=()=>{
this.setState({
show:false
})
}
render(){
if(this.props.msg.length<4){
return (<p></p>);
}
return(
<div>
<Alert variant='danger' show={this.state.show} onClose={this.handleClose} dismissible>
<Alert.Heading>Oh snap! You got an error!</Alert.Heading>
<p>
{this.props.msg}
</p>
</Alert>
</div>
)
}
}
当消息长度小于 4 时,我将返回一个空元素。这确保了当我们最初进入登录页面时,Message 组件不会呈现或登录成功。
主要问题:
我进入登录页面并输入了错误的电子邮件,然后我得到了这个页面。
当我点击模型内的关闭按钮时,它会按预期关闭。但是,问题是,当我再次输入错误的用户名或密码时,我没有收到 Alert。
【问题讨论】:
-
尝试使用 componentDidUpdate(){ this.setState({show:this.props.show}) } 而不是 componentDidMount
标签: javascript reactjs react-bootstrap