여전히 RN에서 배우는 중 ... 스마트 폰 브라우저에서 웹 페이지 를 열기 전에 fetch()
react-native 에서 서버에서 특정 데이터 를 가져 오려고 합니다. 내가 쓴 내용은 다음과 같습니다.
openLink = () => { //Communicate to the server to get an unique key_id
this.state = {urlKey: 'text'}; //Initial state
var params = {
// Some params send by POST to authenticate the request...
};
var formData = new FormData();
for (var k in params) {
formData.append(k, params[k]);
}
fetch(Constants.URL.root+"mobile/authorize_view", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({urlKey:responseJson.document_key}); //Getting the response, and changing the initial state (was 'text' previously)
})
.done();
var urlString = Constants.URL.upload + '/' + this.state.urlKey; // !!Problem : opening in browser with this.state.urlKey = text, and not document_key!!
Linking.canOpenURL(urlString).then(supported => {
if (supported) {
Linking.openURL(urlString);
} else {
console.log('Don\'t know how to open URI: ' + this.props.url);
}
});
}
실제로 보시다시피 내 서버에 특정 키를 요청 합니다 ( urlKey , JSON 개체로 반환 됨 : responseJson.document_key).
모든 것이 서버 부분에서 잘 실행되고 있습니다 . 생성 된 document_key를 데이터베이스에 넣었으므로 올바르게 입력되었는지 확인할 수 있습니다.
문제는 반작용 네이티브 일부입니다 : 브라우저로 웹 페이지를 엽니 this.state.urlKey
로 **text**
인 초기 상태 함수가 있음을 fetch
서버가 보낸 document_key으로 전환해야 ... 나는 무엇을 놓치고?
fetch 문은 비동기식입니다. fetch를 호출하면 다음 실행 줄이 필요하지 .then
않지만var urlString = Constants.URL.upload + '/' + this.state.urlKey;
이 단계 .then
에서 데이터 가져 오기가 완료 this.state.document_key
되지 않으면 채워지지 않습니다. 따라서 오류가 표시되는 이유
대신 해당 코드를 마지막으로 이동하십시오 then
.
openLink = () => { //Communicate to the server to get an unique key_id
this.state = {urlKey: 'text'}; //Initial state
var params = {
// Some params send by POST to authenticate the request...
};
var formData = new FormData();
for (var k in params) {
formData.append(k, params[k]);
}
fetch(Constants.URL.root+"mobile/authorize_view", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({urlKey:responseJson.document_key}); //Getting the response, and changing the initial state (was 'text' previously)
//moved inside then
var urlString = Constants.URL.upload + '/' + this.state.urlKey; // !!Problem : opening in browser with this.state.urlKey = text, and not document_key!!
Linking.canOpenURL(urlString).then(supported => {
if (supported) {
Linking.openURL(urlString);
} else {
console.log('Don\'t know how to open URI: ' + this.props.url);
}
});
})
.done();
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다