2017-12-07 19 views
0

내 프로젝트에서 bcryptjs 라이브러리를 사용하여 암호 해시를 시도하지만 해싱 프로세스에 필요한 기능을 추가 할 때 오류가 발생합니다. 이 링크의 지침을 따르고 있습니다 : bcryptjs instructions.ReactJS 및 bcryptjs로 정의되지 않은 속성 'state'을 읽을 수 없습니다.

아이디어는 내가 SubmitClick 함수를 호출 할 때 제공된 암호를 해시 한 다음 fetch을 사용하여 데이터베이스에 추가하는 것입니다. 나는 ',

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

하지만 그 부분 : 나는 다음 코드 부분을 제거하면

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; 

이 코드가 완벽하게 작동 해싱하지 않고, 다음은 내 CreateUser.js 페이지의 코드는 이 오류에 직면 m :

> 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> 

내 코드에 어떤 문제가 있는지 전혀 알지 못합니다.

답변

1

을 :

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

솔루션 :

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 대신에 그 변수를 사용

한 가지 방법은 여기 또한 arrow function를 사용하는 것입니다

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); 
      }); 
     }); 
    } 
    ..... 
} 
+0

나는 이것을 시도하고 작동합니다! 도와 주셔서 감사합니다 ! –

+0

@rk_Tinelli 기쁘게 생각합니다. 문제가 해결되었습니다 :) –

1

당신은 콜백을 bind 필요 또는 this은 설정되지 않습니다 :

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

또는 화살표 기능 사용 : 당신은 genSalt에 전달 된 콜백 메소드의 문맥을 잃어버린하는

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

나는 이것을 시도하고 작동합니다! 도와 주셔서 감사합니다 ! –