【问题标题】:Cannot read property 'state' of undefined with ReactJS and bcryptjs无法使用 ReactJS 和 bcryptjs 读取未定义的属性“状态”
【发布时间】:2018-05-21 20:06:03
【问题描述】:

我正在尝试使用 bcryptjs 库在我的项目中对密码进行哈希处理,但是当我添加哈希处理所需的函数时,我遇到了一些错误。我正在按照此链接中的说明进行操作:bcryptjs instructions

这个想法是,当我调用SubmitClick 函数时,我必须对提供的密码进行哈希处理,然后使用fetch 将其添加到我的数据库中。这是我的 CreateUser.js 页面的代码:

import React, { Component } from 'react';
import bcrypt from 'bcryptjs';

class CreateUser extends Component {

  constructor(props){
    super(props);
    this.state={
      id:'',
      email:'',
      first_name:'',
      last_name:'',
      personal_phone:'',
      password:'',
      reTypepassword:''
    }
  }

  SubmitClick(){

    if (this.state.password !== this.state.reTypepassword){
      alert('Passwords do not match. Please check your data !');
    } else {

      bcrypt.genSalt(10, function(err, salt) {
          bcrypt.hash(this.state.password, salt, function(err, hash) {
              console.log(hash); 
          });
      });

      fetch('http://localhost:4000/users/', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          //'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: this.state.email,
          first_name: this.state.first_name,
          last_name: this.state.last_name,
          personal_phone: this.state.personal_phone,
          password: this.state.password
        })
      })
      .then(response => response.json())
      .then(parsedJSON => this.setState({id : parsedJSON._id}, function(){
        this.props.history.push({
          pathname : '/get',
          state : { id : this.state.id }
        });
      }))
      .catch(error => alert('Check your data! Some of the values passed aren`t valid'))
    }
  }

  changeID(parsedJSON){
    this.setState({id : parsedJSON._id})
  }

  changeEmail(event){
    this.setState({email : event.target.value})
  }

  changeFname(event){
    this.setState({first_name : event.target.value})
  }

  changeLname(event){
    this.setState({last_name : event.target.value})
  }

  changePhone(event){
    this.setState({personal_phone : event.target.value})
  }

  changePassword(event){
    this.setState({password : event.target.value})
  }

  changeReTPassword(event){
    this.setState({reTypepassword : event.target.value})
  }

  render() {
    return (
      <div id="layout">
        <div id="main">
          <div className="App-header">
              <label htmlFor="title">Create User</label> 
          </div>
          <div className="content" id="content">
            <div className="infos">
              <input id="email" type="text" name="email" placeholder="Email" 
              onChange = {(event)=> this.changeEmail(event)}/>
            </div>
            <div className="infos">
              <input id="f_name" type="text" name="F_name" placeholder="First Name" 
              onChange = {(event)=> this.changeFname(event)}/>
            </div>
            <div className="infos">
              <input id="l_name" type="text" name="L_name" placeholder="Last Name" 
              onChange = {(event)=> this.changeLname(event)}/>
            </div>
            <div className="infos">
              <input id="phone" type="text" name="L_name" placeholder="Personal Phone" 
              onChange = {(event)=> this.changePhone(event)}/>
            </div>
            <div className="infos">
              <input id="senha" type="password" name="senha" placeholder="Password" 
              onChange = {(event)=> this.changePassword(event)}/>
            </div>
            <div className="infos">
              <input id="senha" type="password" name="senha" placeholder="Re-type password" 
              onChange = {(event)=> this.changeReTPassword(event)}/>
            </div>
            <div className="buttons">                                  
              <button type="submit" onClick={(event) => this.SubmitClick()} className="buttonsUser">Submit</button>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default CreateUser;

如果我删除代码的以下部分,代码可以完美运行,无需散列:

  bcrypt.genSalt(10, function(err, salt) {
      bcrypt.hash(this.props.password, salt, function(err, hash) {
          console.log(hash); 
      });
  });

但是对于那部分,我遇到了这个错误:

> CreateUser.js:26 Uncaught TypeError: Cannot read property 'state' of undefined
    at CreateUser.js:26
    at bcrypt.js:155
    at run (setImmediate.js:40)
    at runIfPresent (setImmediate.js:69)
    at onGlobalMessage (setImmediate.js:109)

我搜索了整个 StackOverflow 问题,发现了一些与我的问题相似的问题,并且我尝试使用每个问题中提出的解决方案,但没有任何改变。以下是问题链接供参考:Question1Question2Question3Question4

我试图在类构造函数中绑定我的函数,如下所示,但得到了同样的错误。

  constructor(props){
    super(props);
    this.SubmitClick = this.SubmitClick.bind(this);
    this.state={
      id:'',
      email:'',
      first_name:'',
      last_name:'',
      personal_phone:'',
      password:'',
      reTypepassword:''
    }
  }

我试图内联绑定我的函数,在这种情况下,当我单击按钮时实际上没有发生任何事情,这很奇怪。

    <div className="buttons">                                  
      <button type="submit" onClick={(event) => this.SubmitClick.bind(this)} className="buttonsUser">Submit</button>
    </div>

我不知道我的代码出了什么问题,有什么建议吗?

【问题讨论】:

    标签: reactjs hash bcrypt


    【解决方案1】:

    你需要bind回调,否则this不会被设置:

      bcrypt.genSalt(10, function(err, salt) {
          bcrypt.hash(this.state.password, salt, function(err, hash) {
              console.log(hash); 
          });
      }.bind(this));
    

    或者使用箭头函数:

      bcrypt.genSalt(10, (err, salt) => {
          bcrypt.hash(this.state.password, salt, function(err, hash) {
              console.log(hash); 
          });
      });
    

    【讨论】:

      【解决方案2】:

      您正在丢失传递给genSalt 的回调方法中的上下文:

      bcrypt.genSalt(10, function(err, salt) {
          bcrypt.hash(this.state.password, salt, function(err, hash) {
                console.log(hash); 
          });
      });
      

      解决方案:

      一种方法是在这里也使用arrow function

      bcrypt.genSalt(10, (err, salt) => {
          bcrypt.hash(this.state.password, salt, (err, hash) => {
                console.log(hash); 
          });
      });
      

      或者使用.bind(this):

      bcrypt.genSalt(10, function(err, salt) {
          bcrypt.hash(this.state.password, salt, function(err, hash) {
                console.log(hash); 
          });
      }.bind(this));
      

      或者使用额外的变量,并使用该变量代替this

      SubmitClick(){
          if (this.state.password !== this.state.reTypepassword){
            alert('Passwords do not match. Please check your data !');
          }else {
      
              let that = this;    //here
      
              bcrypt.genSalt(10, function(err, salt) {
                  bcrypt.hash(that.state.password, salt, function(err, hash) {
                      console.log(hash); 
                  });
              });
          }
          .....
      }
      

      【讨论】:

        猜你喜欢
        • 2021-11-18
        • 2019-10-08
        • 2021-08-06
        • 2019-06-08
        • 2021-11-28
        • 2022-01-12
        • 2019-07-25
        • 2020-11-05
        相关资源
        最近更新 更多