我正在尝试创建一个注册页面,我想在注册帐户后进行OTP验证。 就像现在的大多数注册一样,在某处创建帐户后,您将获得一个激活链接,当您单击该链接时,您的帐户将被激活,所以这也是我在我的注册页面中想要的,但带有 OTP。
我希望我的注册就像,在创建帐户后,如果 api 发送"验证电子邮件"作为响应,那么我们将被重定向到 otp 验证页面,但我不确定如何实现它。 OTP 页面知道输入的 OTP 适用于我们刚刚用于在我的网站中创建帐户的这封电子邮件。我们是否应该将电子邮件作为注册元素中的道具发送.js像
else if (response.data === "verifyemail") {
return <Redirect to="/verifyOtp" email={this.state.email}/ />;
}
还是我做错了?
这是 OTP 验证页面
import React, { Component } from "react";
import { Redirect } from "react-router-dom";
class VerifyOTP extends Component {
constructor(props) {
super(props);
this.state = {
otp: ""
};
this.onchange = this.onchange.bind(this);
}
onchange(e) {
this.setState({ [e.target.name]: e.target.value });
}
performVerify = async event => {
event.preventDefault();
var data = {
emailid: this.props.email,
otp: this.state.registrationotp
};
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json"
},
body: JSON.stringify(data)
};
const url = "/api/verifyemail";
try {
const response = await fetch(url, options);
const result = await response.json();
console.log(result);
if (result.data === "verified") {
return <Redirect to="/dashboard/" />;
}
} catch (error) {
console.error(error);
}
};
render() {
return (
<div>
<input
type="text"
name="otp"
placeholder="emnter otp"
onChange={this.onchange}
/>
<br />
<button type="submit" onClick={event => this.performVerify(event)}>
Submit
</button>
<hr />
</div>
);
}
}
export default VerifyOTP;
我试图将此代码从angularjs代码转换为reactjs代码,因为它以前是在angularjs上制作的
$scope.register=function(){
$scope.newuser={
'username':$scope.name,
'password':$scope.password,
'email':$scope.emailid
}
return $http.post('/api/register',$scope.newuser).then(function(response,status){
if(response.data=='redirect'){
$window.location.href="/home";
}else if(response.data=='verifyemail'){
angular.element(document.querySelector('#verifyemailbtn')).click();
}else {
window.alert(response.data);
}
});
}
});
$scope.verifyemailotp=function(){
$http.post('/api/verifyemail',{'emailid':$scope.emailid,'otp':$scope.registrationotp}).then(function(response,status){
if(response.data=='verified'){
$window.location.href="/home";
}
});
}
我想知道直到我所做的是否正确? 如果有任何错误,请告诉我我错在哪里。 整个代码也在代码沙盒上
https://codesandbox.io/s/beautiful-shirley-nn235
以下是你做错的事情:
使用React-RouterRedirect
我们不使用可以在渲染中使用的组件。 对于以编程方式更改路由,我们必须根据需要使用history.push
或history.replace
。
所以替换
<Redirect
to={{
pathname: "/verifyOtp",
state: { email: "this.state.email" }
}}
/>
跟
this.props.history.push("/verifyOtp", { email: this.state.email });
当您将某些内容传递给状态时,params
和state
状态存在差异,您可以通过props.location.state
访问,如果您想更改路由参数,则必须仅以这种方式传递路由,即location.push('/verifyOtp?email=test')
这一点,我们必须访问props.match.params.email
.
这是更新的沙盒 https://codesandbox.io/s/jolly-turing-inx3w
其他建议:
不要使用var
使用const
,let
没有差异黑白onClick={event => this.performLogin(event)}
onClick={this.performLogin}
您可以否定不需要的功能