我有 Node JS 和 Express API,它接受电子邮件作为 URI 参数: http://localhost:5000/otp/get-passc/:email
例如: http://localhost:5000/otp/get-passc/${this.state.passAccount.email.toString()} 与 submitRequest 方法相同。
我的前端是 React:
这是我的 React 代码:
class FormClass extends React.Component{
constructor(props){
super(props);
this.state = {
passAccount: {
email: "Email",
password: "Password"
},
errorMessage: ''
};
}
submitRequest = (event) =>{
this.state.passAccount.email === 'Email' ? this.setState({errorMessage:'Please enter a valid email'}) : axios.post(`http://localhost:5000/otp/get-passc/${this.state.passAccount.email.toString()}`);
console.log(this.state.passAccount.email);
event.preventDefault();
}
handleChange = (event) =>{
console.log(`input detected`);
let request = this.state.passAccount;
request[event.target.name] = event.target.value;
this.setState({passAccount: request});
}
handleSubmit = (event) =>{
event.preventDefault();
}
render(){
return(
<Form onSubmit={() => this.handleSubmit}>
<Form.Group>
<Form.Label>Email Address</Form.Label>
<Form.Control type="text" value={this.state.email} onChange={this.handleChange} />
</Form.Group>
<Form.Group>
<Form.Label>Password</Form.Label>
<Form.Control type="text" value={this.state.passcode} onChange={this.handleChange}/>
</Form.Group>
<Button type="submit" onClick={() => this.submitRequest}>Get OTP</Button>
</Form>
);
}
}
export default FormClass;
我的问题:
当我单击“获取 OTP”按钮时,我想使用 Axios 向在电子邮件字段中输入的电子邮件发送 POST 请求。 但是它不起作用。
setState 无法对电子邮件字段使用 handleChange 函数,有什么问题?
答案 0 :(得分:0)
您不用调用 submitRequest
,只需更新:
onClick={() => this.submitRequest()}
您以错误的方式更新状态。
this.setState({passAccount: {...this.state.passAccount, event.target.name: event.target.value}});