javascript - 在reactjs中验证登录页面

标签 javascript reactjs react-router

我想将 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/

相关文章:

javascript - 如何使用播放、暂停、重置功能控制多段线上的符号(使用 Google Map API)

javascript - 在 Jest 测试中等待 Promise.all

reactjs - react : Unique keys and optimistic updating

javascript - 如何在React Router v6中获取嵌套路由中的参数?它不适用于我的项目

reactjs - JSX 语法和 React.createElement() 之间的差异

javascript - 在 DOM 中单击时获取下一个也是唯一一个类

javascript - 使用 jQuery 在 Explorer 8 中的 <td> 圆 Angular ?

javascript - jQuery Datatables - 单击该行中的按钮时如何获取该行的索引

reactjs - 测试时,导致 React 状态更新的代码应该包装到 act(...) 中 - 使用简单的 React-native 嵌套屏幕/组件和 jest axios

javascript - React Router URL 抛出参数错误