Tan*_*byn 6 react-native react-native-android react-native-ios
使用React Native Fetch API时遇到问题。很多次请求失败。我有高速连接。但是很多次失败了。该问题正在android和ios中同时发生。
const shoppingApi = 'myserverlink';
async function Sendshoppinapi(data) {
try {
let response = await fetch(shoppingApi, {
method: 'POST',
headers: {
'Accept': 'application/json',
'content-type':'multipart/form-data'
},
body: data
});
let responseJson = await response.json();
return responseJson;
}
catch (error) {
Alert.alert(error.toString())
}
}
export {Sendshoppinapi};
Run Code Online (Sandbox Code Playgroud)
我发送服务器作为后期请求的数据
add_to_wishlist = (item,index) => {
{
let data = new FormData();
data.append('methodName', 'add_to_wishlist');
data.append('user_id', global.userid)
data.append('item_id', this.props.navigation.state.params.itemid.toString())
Sendshoppinapi(data).then((responseJson)=>{
console.warn(responseJson);
if(responseJson.responseCode == '200'){
this.setState({fav:false})
Alert.alert('SHOPPING','Item added to wishlist successfully.',[{text: 'OK',},],{ cancelable: false })
}
else{
this.setState({fav:false})
Alert.alert('SHOPPING','Item already .',[{text: 'OK',},],{ cancelable: false })
}
})}
}
Run Code Online (Sandbox Code Playgroud)
将 then() 函数与 Promise 一起使用。(请求的代码片段)
fetch(shoppingApi, {
method: 'POST',
headers: {
'Accept': 'application/json',
'content-type':'multipart/form-data'
},
body: data
})
.then((resp) => {
return resp.json()
})
.then((resp) => {
//resp contains your json data
});
Run Code Online (Sandbox Code Playgroud)
你还可以让你的函数返回一个 Promise,并将其与 then() 一起使用:
function sendShoppingApi(data) {
return new Promise((resolve, reject) => {
fetch(shoppingApi, {
method: 'POST',
headers: {
'Accept': 'application/json',
'content-type':'multipart/form-data'
},
body: data
})
.then((resp) => {
return resp.json();
})
.then((resp) => {
resolve(resp);
/*
you should also check if data is valid, if something went wrong
you can reject the promise:
if(!dataOK)
reject("error message");
*/
});
});
}
Run Code Online (Sandbox Code Playgroud)
所以现在你可以做这样的事情:
sendShoppingApi(data)
.then((resp) => {
//do stuff with your data
})
.catch((err) => {
//handle error
});
Run Code Online (Sandbox Code Playgroud)
更新
可能与此重复:React Native fetch() Network Request Failed
归档时间: |
|
查看次数: |
8125 次 |
最近记录: |