그래서 방금 생성 된 객체를 반환하는 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
에 추가합니다. 하지만 자바 스크립트의 비동기 문제로 인해이 작업을 올바른 순서로 수행 할 수 없다고 생각합니다. 어떤 아이디어?
첫 번째 방법은 본체가 정의되어 있지 않습니다. – anderish
잘못된, 약간의 오타 : 'body'대신'data'를 사용하십시오. 그에 따라 내 대답을 편집했습니다. – yuantonito