2017-10-29 5 views
0

그래서 방금 생성 된 객체를 반환하는 POST API이 있고 객체 정보를 얻고 싶습니다. reactjs.ReactJs 콜백에서 변수를 얻으려고 시도

createItem(item){ 
    let temp; 
    // POST to DB 
    fetch(url(this.props.api), { 
     method:"POST", 
     headers: { 
      'Accept': 'application/json', 
      'Content-Type': 'application/json', 
     }, 
     body: JSON.stringify({ 
      name: item, 
      isCompleted:false 
     }) 
    }).then(function (response) { 
     return response.json() 
    }).then(function (body) { 
     temp = body; // got the objects information 
     console.log(temp); 
    }); 

    console.log(temp); 

    this.state.bucket_list.push({ 
     name: item, 
     isCompleted: false 
    }); 
    this.setState({bucket_list: this.state.bucket_list}); 

} 

이것은 내가 무엇을하지만 나는 then 함수 외부 데이터를 추출 할 수 있습니다. 정보를 얻은 후에 setState으로하고 새로 만든 객체를 내 state: bucketlist에 추가합니다. 하지만 자바 스크립트의 비동기 문제로 인해이 작업을 올바른 순서로 수행 할 수 없다고 생각합니다. 어떤 아이디어?

답변

1

답변을 제공하기 전에 상태를 직접 변이시키는 것이 반 패턴으로 간주된다는 것을 알아야합니다. 대신 개체를 불변으로 간주해야합니다.

대신에 :

1. 어쨌든

this.state.bucket_list.push({ 
    name: item, 
    isCompleted: false 
}); 
this.setState({bucket_list: this.state.bucket_list}); 

당신은 했어야

this.setState({ 
    bucket_list: [ 
    ...this.state.bucket_list, 
    { 
     name: item, 
     isCompleted: false 
    }, 
    ] 
}); 

, 내가 당신에게 당신의 유스 케이스를 처리하는 두 가지 wayts을 줄 수 있도록 비동기/대기 (권장)

async/await을 사용하면 다음 단계로 진행하기 전에 지시 사항을 완료 할 때까지 기다릴 수 있습니다. 사용

async createItem(item){ 
     // POST to DB 
     const data = await fetch(url(this.props.api), { 
     method:"POST", 
     headers: { 
      'Accept': 'application/json', 
      'Content-Type': 'application/json', 
     }, 
     body: JSON.stringify({ 
      name: item, 
      isCompleted:false 
     }) 
     }); 

     this.setState({ 
     bucket_list: [ 
      ...this.state.bucket_list, 
      data, 
     ], 
     }); 
    } 

2. 보관할는 then로 가져오고 그것은 함수가 자신의 this이 없을 수 있습니다 화살표 기능

를 사용합니다. 그렇기 때문에 arrow function 안에 this.setState을 사용할 수 있습니다.

createItem(item){ 
     // POST to DB 
     fetch(url(this.props.api), { 
     method:"POST", 
     headers: { 
      'Accept': 'application/json', 
      'Content-Type': 'application/json', 
     }, 
     body: JSON.stringify({ 
      name: item, 
      isCompleted:false 
     }) 
     }) 
     .then(response => response.json()) 
     .then(data => { 
     this.setState({ 
      bucket_list: [ 
      ...this.state.bucket_list, 
      data, 
      ], 
     }); 
     }); 
    } 

주 2 : 사용법이 간단하면이 방법을 계속 사용할 수 있습니다. 그렇지 않으면 당신은 확실히 봐야한다 redux

+0

첫 번째 방법은 본체가 정의되어 있지 않습니다. – anderish

+0

잘못된, 약간의 오타 : 'body'대신'data'를 사용하십시오. 그에 따라 내 대답을 편집했습니다. – yuantonito

관련 문제