2017-12-06 9 views
1

ReactJS를 사용하여 기본 웹 애플리케이션을 설정하고 있습니다. 지금 당장 POST 요청을 사용하여 데이터베이스에 데이터를 추가 할 수 있습니다. 문제는, 백엔드 응답에서 전달한 모든 데이터와 데이터베이스의 _id를 가진 JSON을 보냅니다. 이 _id를 가져와 내 상태로 저장해야 웹 애플리케이션의 다음 URL로 전달할 수 있습니다. 그건 내 POST 요청에 대한 코드입니다 :parsedJSON에서 데이터를 가져 오는 방법 reactJS

SubmitClick(){ 

    if (this.state.password !== this.state.reTypepassword){ 
     alert('Passwords do not match. Please check your data !'); 
    } else { 
     //console.log(this.state); //debug only 
     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 => console.log(parsedJSON._id)) 
     .catch(error => alert('Check your data', error)) 
     .then(this.props.history.push('/get')) // change page layout and URL 
    } 
    console.log(this.state.id); //debug to see if the _id is saved in my state 
    } 

여기 내 생성자 :

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

내가 function(parsedJSON){this.state.id : parsedJSON._id}를 사용하여, this.setState()을 사용 parsedJSON 후 함수를 호출했습니다.

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

.then(parsedJSON => console.log(parsedJSON._id)).then(parsedJSON => this.cahngeID(parsedJSON))에 변화 : 나는 새로운이 같은 기능을 시도했다. 하지만 그 중 아무도 작동하지 ...

나는이 값을 볼 수 있도록 .then(parsedJSON => console.log(parsedJSON._id)) 코드를 남겨 두었고, 제 콘솔에서 완벽하게 인쇄되었습니다. {"email":"[email protected]","first_name":"TESTER","last_name":"Testing","personal_phone":"(55) 2020-5252","password":"12345","_id":"5a27f511cd7d7a0db8ab65b9"}

가 어떻게 내 응답에서 "_id"를 얻을 수 있습니다 : 여기

는 응답의 예 내 백엔드로 보낼 수있다?

+0

원래 this.setState() 호출 구문은 무엇입니까? 또한 _id가 현재()에있는 상태로 저장되었는지, 현재 올바른 결과를 제공하지 않는지 확인하기 위해 디버그를 이동하려고한다고 생각합니다. – Rnice4christ

+0

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

답변

1

this.state 속성을 직접 만지지 않아야합니다. React가 변경 사항을 추적 할 수 있도록 this.state이 업데이트되었을 때이를 알아야하기 때문에 React가 오류를 던집니다. 속성을 직접 조작하면이 작업을 수행 할 수 없습니다. 그래서 우리는 React.Component#setState입니다. "얕은"버전이 가장 일반적으로 사용되며, 여기에서 상태로 병합 될 객체를 전달합니다. 예를 들어, 다음과 같은 : 그 반작용이 상태가 업데이트 될 때 추적 할 얻을 제외하고

Object.assign(this.state, { id: parsedJSON._id }); 

:

.then(parsedJSON => this.setState({ id: parsedJSON._id })) 

은 동일합니다.

setState도 비동기이며 두 번째 매개 변수로 콜백을받습니다. 당신은 read more about that here 일 수 있습니다. 자바 스크립트는 우리의 방법에 '이'의 인스턴스 값을 결합하지 않기 때문에

this.SubmitClick = this.SubmitClick.bind(this); 

: 생성자의 끝에서 아래의 주석 사항에 따라

, this other Stack Overflow question was helpful to the OP (Why calling react setState method doesn't mutate the state immediately?)

+0

그래서'.then (parsedJSON => this.setState ({id : parsedJSON._id}))를 사용하는 대신' 'Object.assign (this.state, {id : parsedJSON._id});)을 사용하시오. 다음과 같은 오류가 발생했습니다 :'Line 40 : 'parsedJSON'은 no-undef'로 정의되지 않았습니다. '.then (parsedJSON => Object.assign (this.state, {id : parsedJSON._id})) '을 사용하면 실제로 아무것도 변경되지 않습니다. –

+1

안녕하세요, 알렉스, 당신이 제공 한 정보를 사용하여 나는 코드에서 계속 진행하기 전에 즉시 상태를 변경하는 방법을 인터넷에서 검색 한 다음 setState의 콜백 함수가 나타납니다. 나는 내 질문을 당신의 정보와 함께 해결하는데 도움이되는이 질문을 발견했다 : [질문] (https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the- 주 - 즉시) 도움을 주셔서 감사합니다! –

0

는 코드 줄을 추가합니다.

+0

이것을 생성자에 추가하고 질문에서 언급 한 코드를 시도했지만 실제로 변경된 사항은 없습니다 ... 코드에서 변경해야합니까? –

관련 문제